try catch finally執行順序

2021-10-23 12:14:48 字數 2391 閱讀 7482

擼**的時候經常會用到try catch finally,但是如果不理解其中的真正用法 可能程式就會出問題哦,在這裡測試幾種情況下的返回值

test1: 最簡單的在try返回

public

static

final

inttest1()

catch

(exception e)

finally

}public

static

void

main

(string[

] args)

輸出結果:

tryfinally

1

說明: 執行了finally裡面語句 ,但是返回的結果是try裡面的1

疑問:明明執行了finally裡面的 x=3 語句,返回的結果為什麼是1尼,在這裡讀者可能會產生乙個疑問,是否finally就對try裡面的變數不產生影響尼,我們看下面乙個例子:

public

static

final

inttest1()

catch

(exception e)

finally

}public

static string[

]testfinally()

catch

(exception e)

finally

return null;

}public

static

void

main

(string[

] args)

結果:finally

[try

,finally

]

說明:可以finally對陣列s[1]的值進行了更改,所以 上面紅字的說法是不正確的

總結test1、test1.1 我們可以得到結論 針對上面的情況 如果變數是基本型別的話 是不會產生影響的,如果是非包裝型別,則會更改

test2:在finally裡面新增return

public

static

final

inttest3()

catch

(exception e)

finally

}結果:

tryfinally

3

test3: 在try裡面丟擲異常,執行catch**塊

public

static

final

inttest4()

catch

(exception e)

finally

}結果:

trycatch

finally

3

說明:執行了catch finally 裡面的**塊 但是返回的還是finally裡面的return

總結test1、test2、test3:

通過這三個例子我們可以發現,當try catch finally 裡面都有return的時候,最終返回的是finally的結果

test4: 在try裡面丟擲異常,執行catch**塊 去掉finally裡面的return

public

static

final

inttest5()

catch

(exception e)

finally

}結果:

trycatch

finally

2

說明:所有語句都執行了 最後返回的是finally的結果

總結test1 2 3 4:

無論發生異常與否,finally語句塊一定在return之前執行。

以下結論基於如下前提:try的return語句在發生異常語句之後、方法有返回值。

① 當finally語句塊中存在return語句時,此時無論是否發生異常,都以該return語句為準,其他的return語句將不起作用。

② 當發生異常時,try存在return語句,catch存在return語句,以catch中的return語句為準,此時在finally語句塊中的修改將不起作用。

③ 當發生異常時,try存在return語句,catch不存在return語句,方法在最後存在return語句,以該return語句為準,此時在catch和finally的修改會起作用。

④ 不發生異常時,try存在return語句,不管是catch存在return語句還是方法最後存在return語句,都以try中的return語句為準,此時在catch、finally中的修改將不起作用。

try catch finally執行順序

public class test public static int ma catch exception e finally 說明 不出現異常情況 執行順序 try finally 出現異常情況 執行順序 try catch finally try中有返回語句,沒有異常 執行順序 try ret...

try catch finally執行順序

結論 1 不管有木有出現異常,finally塊中 都會執行 2 當try和catch中有return時,finally任會執行 3 finally是在return表示式運算後前執行的,所以函式返回值是在finally執行前確定的 4 finally中最好不要包含return,否則程式會提前退出,返回...

try catch finally使用體會

try catch finally public class finallytest static int test finally 結果是2。在try語句中,在執行return語句時,要返回的結果已經準備好了,就在此時,程式轉到finally執行了。在轉去之前,try中先把要返回的結果存放到不同於...