2013-03-06 75 views
1

標題有點誤導,但這個問題對我來說很直截了當。我有try-catch-finally塊。只有當從try塊中拋出異常時,我纔想執行finally塊中的代碼。代碼的,現在的結構是:C# - 從finally子句中處理異常

try 
{ 
    //Do some stuff 
} 
catch (Exception ex) 
{ 
    //Handle the exception 
} 
finally 
{ 
    //execute the code only if exception was thrown. 
} 

現在我能想到的是設置一個標誌就像唯一的解決辦法:

try 
{ 
    bool IsExceptionThrown = false; 
    //Do some stuff 
} 
catch (Exception ex) 
{ 
    IsExceptionThrown = true; 
    //Handle the exception 
} 
finally 
{ 
if (IsExceptionThrown == true) 
    { 
    //execute the code only if exception was thrown. 
    } 
} 

這並不是說我看到這個東西不好,但不知道是否有是另一種(更好的)方法來檢查是否存在拋出的異常?

+1

你爲什麼不把代碼在catch()部分? – Larry 2013-03-06 08:56:26

+0

你要找的是'fault',它存在於CLR中,但從未在C#中實現過。 – 2013-03-06 08:58:32

+0

@Laurent - 我想象一下,如果有多個'catch'子句,那麼一個實際的用法就是,如果發生任何異常,那麼應該執行的一些通用代碼將是一個更實際的例子。 – 2013-03-06 09:50:31

回答

12

什麼是這樣的:

try 
{ 
    // Do some stuff 
} 
catch (Exception ex) 
{ 
    // Handle the exception 
    // Execute the code only if exception was thrown. 
} 
finally 
{ 
    // This code will always be executed 
} 

這就是Catch塊的製作!

+0

+1清楚地顯示如何終於工作。 – Larry 2013-03-06 09:06:23

4

請勿爲此使用finally。它適用於執行總是的代碼。

到底是什麼區別,在何時執行方面,我看不到任何

之間

//Handle the exception 

//execute the code only if exception was thrown. 

0

無論是否發現任何異常,Try/Catch語句的finally部分總是被觸發。我建議你不要在這種情況下使用它。

try 
{ 
    // Perform Task 
} 
catch (Exception x) 
{ 
    //Handle the exception error. 

} 
Finally 
{ 
    // Will Always Execute. 
} 
2

你不需要畢竟finally

try 
{ 
    //Do some stuff 
} 
catch (Exception ex) 
{ 
    //Handle the exception 
    //execute the code only if exception was thrown. 
}