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塊總會被執行。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章