java中finally关键字的用处

时间:2023-01-14 18:23:29
在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块总会被执行。