标题有点误导,但这个问题对我来说很直截了当。我有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