try-catch-finally,trycatch
通過中間代碼窺探try-catch-finally本質:
class Program { static void Main(string[] args) { Program p = new Program(); Console.WriteLine(p.Test1()); //Console.WriteLine(p.Test2()); Console.Read(); } //結果為:3 private TestClass Test1() { TestClass tc = new TestClass(); try { tc.testVar = 2; return tc; } catch (Exception) { throw; } finally { tc.testVar = 3; } } //結果為:2 private int Test2() { int test = 1; try { test = 2; return test; } catch (Exception) { throw; } finally { test = 3; } } } class TestClass { public int testVar = 111; public override string ToString() { return testVar.ToString(); } }
調用方法Test1,中間代碼賦予本地變數的僅是一個引用,所以finally的操作是有影響的,其中間代碼為:
調用方法Test2,try中return時,已經將返回值儲存在中間代碼的本地變數中,而不再是源碼中變數test,所以finally的操作是無效的。其中間代碼為:
java中try-catch-finally塊的代碼運行順序是怎的?
繼續運行
try{
拋異常的語句
}catch(捕獲異常){
列印堆棧
}
finally{
一般是釋放資源(例如你在try 裡開啟了一個檔案,出了異常,沒有關閉它,finally裡面寫的就像這種)
finally裡面的語句不管catch執行不執行都會走的
}
下面的語句正常運行,不影響
程式中使用try-catch-finally語句結構處理異常的方法
從try程式塊中得到異常,然後再catch塊中做處理(一般是拋出,資料復原,寫日誌等等),在finally塊中的程式是最後執行的(不論是否前面的程式拋出異常)。