1.首先明確一點,就是不管怎樣,finally一定會執行,即使程序有異常,並且在catch中thorw 了 ,finally還是會被執行。
2.當try和catch中有return時,finally仍然執行。
3.finally是在return后面的表達式運算完之后執行的,在執行完return時 ,程序並沒有跳出,而是進入到finally中繼續執行,
如果在finally如果對返回值進行了重新賦值,分為兩種情況:
(1)當返回值是值類型(包括string類型,雖然是引用類型,這是特殊的個例)時,返回的值不受影響,
就是在trycatch時,返回的值已經確定了。
(2)當返回值是引用類型時,會影響到返回值,eg:
public static string[] TestYinYong() { string[] arr = { "one", "two" }; try { throw new Exception(); } catch (Exception) { return arr; } finally { arr[1] = "three"; } }
此時返回的值是:{ "one", "three" };
4.finally中不能有return語句,編譯都無法通過,提示:控制不能離開finally子句主體
參考:
http://m.blog.csdn.net/kavensu/article/details/8067850
http://blog.csdn.net/jiankunking/article/details/38750023