標題有點誤導,但這個問題對我來說很直截了當。我有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.
}
}
這並不是說我看到這個東西不好,但不知道是否有是另一種(更好的)方法來檢查是否存在拋出的異常?
你爲什麼不把代碼在catch()部分? – Larry 2013-03-06 08:56:26
你要找的是'fault',它存在於CLR中,但從未在C#中實現過。 – 2013-03-06 08:58:32
@Laurent - 我想象一下,如果有多個'catch'子句,那麼一個實際的用法就是,如果發生任何異常,那麼應該執行的一些通用代碼將是一個更實際的例子。 – 2013-03-06 09:50:31