标题有点误导,但这个问题对我来说似乎非常简单。我有try-catch-finally
阻止。我只想在finally
块中抛出异常时才在try
块中执行代码。现在代码的结构是:
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.
}
}
并不是说我看到了一些不好的东西,但想知道是否还有另一种(更好的)方法来检查是否存在抛出的异常?
答案 0 :(得分: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
阻止的内容!
答案 1 :(得分:4)
请勿使用finally
。它适用于始终执行的代码。
之间在执行时间方面究竟有什么区别
//Handle the exception
和
//execute the code only if exception was thrown.
我看不到任何。
答案 2 :(得分:2)
毕竟你不需要finally
:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
//execute the code only if exception was thrown.
}
答案 3 :(得分:0)
无论是否找到任何异常,始终会触发Try / Catch语句的Finally部分。我建议你不要在这种情况下使用它。
try
{
// Perform Task
}
catch (Exception x)
{
//Handle the exception error.
}
Finally
{
// Will Always Execute.
}