1

假設我有一些C#代碼:執行順序和finally塊

try { 
    Method1(); 
} 
catch(...) { 
    Method2(); 
} 
finally { 
    Method3(); 
} 
Method4(); 
return; 

我的問題是,只要沒有異常被拋出,將方法3()進行方法4(),或之前執行是否只在return,continuebreak聲明之前執行finally塊?

+6

這似乎是微不足道的測試。 – David

+0

我可以知道爲什麼你不寫一個簡單的控制檯應用程序來查看會發生什麼以及按什麼順序? – CodingYoshi

+0

對不起,我是一個初學者開發者,我沒有想出自己嘗試的想法。在谷歌搜索後,我找不到答案,所以我決定在這裏提問。 – serious6

回答

5

是的,try-catchfinally塊將按照您預期的順序執行,然後執行到代碼的其餘部分(完成整個try-catch-finally塊之後)。

您可以將整個塊視爲一個單獨的組件,其功能與任何其他方法調用一樣(其代碼在其之前和之後執行)。

// Execute some code here 

// try-catch-finally (the try and finally blocks will always be executed 
// and the catch will only execute if an exception occurs in the try) 

// Continue executing some code here (assuming no previous return statements) 

try 
{ 
    Console.WriteLine("1"); 
    throw new Exception(); 
} 
catch(Exception) 
{ 
    Console.WriteLine("2"); 
} 
finally 
{ 
    Console.WriteLine("3"); 
} 
Console.WriteLine("4"); 
return; 

您可以see an example of this in action here其產生以下輸出:

1 
2 
3 
4 
4

序列將總是

try 
--> catch(if any exception occurs) 
--> finally (in any case) 
--> rest of the code (unless the code returns or if there is any uncaught exceptions from any of the earlier statements) 

有用的資源:https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

+1

其餘代碼也會因未捕獲的異常而跳過。 – juharr

+0

@juharr正確,編輯我的答案! – Sameer

1

我的問題是,只要沒有異常被拋出,將方法3()進行方法4()之前執行,

是,Method3Method4因爲之前是否異常執行拋出或不拋出,執行將進入finally塊,然後從那裏繼續。

還是隻是在返回,continue或break語句之前執行finally塊?

不,它總是在try塊之後執行,無論是否存在異常。

着力點

如果你有這樣的:

try 
{ 
    DoOne(); 
    DoTwo(); 
    DoThree(); 
} 
catch{ // code} 
finally{ // code} 

如果一個異常被拋出DoOne()然後DoTwo()DoThree()將永遠不會被調用。因此,不要認爲整個try塊將始終執行。實際上,只有在拋出異常之前的部分纔會被執行,然後執行到catch塊。

終於會永遠執行 - 儘管是否有例外。