天天看點

C#中try catch finally的執行順序(轉載)

1.首先明确一點,就是不管怎樣,finally一定會執行,即使程式有異常,并且在catch中thorw 了 ,finally還是會被執行。

2.當try和catch中有return時,finally仍然執行。

3.finally是在return後面的表達式運算完之後執行的,在執行完return時 ,程式并沒有跳出,而是進入到finally中繼續執行,

  如果在finally如果對傳回值進行了重新指派,分為兩種情況:

(1)當傳回值是值類型(包括string類型,雖然是引用類型,這是特殊的個例)時,傳回的值不受影響,

        就是在trycatch時,傳回的值已經确定了。

(2)當傳回值是引用類型時,會影響到傳回值,eg:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

​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子句主體

個人建議: 定義一個變量或對象儲存需要傳回的值,try、catch中不要return,在函數末尾retrun。

這樣即使在finally中改變了傳回值,從上到下流程也是清晰的。

樹立目标,保持活力,gogogo!

​public​

​static​

​string​

​[] TestYinYong()​

​{​

​string​

​[] arr = { ​

​"one"​

​, ​

​"two"​

​};​

​try​

​{​

​throw​

​new​

​Exception();​

​}​

​catch​

​(Exception)​

​{​

​return​

​arr;​

​}​

​finally​

​{​

​arr[1] = ​

​"three"​

​;​

​}​

​}​

繼續閱讀