2013-03-06 71 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. 
}