java中finally关键字的用处

在java中的finally关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行,写个例子来说明下:
package com.teedry.base;

public class TryAndFinallyTest {

	public static void main(String[] args) throws Exception{
		try{
		int a = testFinally(2);
		System.out.println("异常返回的结果a:"+a);
		}catch(Exception e){
			int b = testFinally(1);
			System.out.println("正常返回的结果b:"+b);
		}
		int b = testFinally(3);
		System.out.println("break返回的结果:"+b);
		
		 b = testFinally(4);
		System.out.println("return返回的结果:"+b);
		
	}
	
	static int testFinally(int i) throws Exception{
		int flag = i;
		try{//一旦进去try范围无论程序是抛出异常或其它中断情况,finally的内容都会被执行
			switch(i){
				case 1:++i;break;//程序 正常结束
				case 2:throw new Exception("测试下异常情况");
				case 3:break;
				default :return -1;
			}
		}finally{
			System.out.println("finally coming when i="+flag);
		}
		return i;
	}
}


执行结果如下:

finally coming when i=2
finally coming when i=1
正常返回的结果b:2
finally coming when i=3
break返回的结果:3
finally coming when i=4
return返回的结果:-1

 

结果说明无论上述什么情况,finally块总会被执行。 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: JAVA关键字包括:abstract、continue、for、new、switch、assert、default、goto、package、synchronized、boolean、do、if、private、this、break、double、implements、protected、throw、byte、else、import、public、throws、case、enum、instanceof、return、transient、catch、extends、int、short、try、char、final、interface、static、void、classfinally、long、strictfp、volatile。 ### 回答2: Java关键字是指被Java编程语言保留用于特定用途的词汇,这些关键字具有特殊含义并且不能用作标识符(如变量、类名等)。Java关键字有以下几个: 1. 基础类型关键字:包括byte、short、int、long、float、double、boolean、char等,用于声明基本数据类型的变量。 2. 控制流程关键字:包括if、else、switch、case、default、for、while、do、break、continue、return等,用于控制程序的流程和决策。 3. 修饰符关键字:包括public、private、protected、static、final、abstract、synchronized等,用于修饰类、方法和变量的访问权限、行为和特性。 4. 类与对象关键字:包括class、interface、extends、implements、new、this、super等,用于定义类和接口以及操作对象和实例。 5. 异常处理关键字:包括try、catch、finally、throw、throws等,用于处理程序的异常情况。 6. 特殊关键字:包括void、null、true、false等,用于表示一些特殊的值和类型。 7. 保留关键字:包括const、goto等,虽然Java保留了这些关键字,但是并没有被使用。 了解和掌握这些关键字对于编写Java程序和理解Java源代码非常重要,因为这些关键字在语言具有固定的含义和用途。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值