C# - finally子句中的异常处理

时间:2013-03-06 08:53:48

标签: c# exception-handling

标题有点误导,但这个问题对我来说似乎非常简单。我有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.
  }
}

并不是说我看到了一些不好的东西,但想知道是否还有另一种(更好的)方法来检查是否存在抛出的异常?

4 个答案:

答案 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.
}