1

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

4 回答 4

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块的用途!

于 2013-03-06T08:55:59.933 回答
4

不要finally用于这个。它适用于应始终执行的代码。

就何时执行而言,两者之间到底有什么区别

//Handle the exception

//execute the code only if exception was thrown.

我什么都看不到。

于 2013-03-06T08:55:58.587 回答
2

finally毕竟你不需要:

try
{
  //Do some stuff
}
catch (Exception ex)
{
  //Handle the exception
  //execute the code only if exception was thrown.
}
于 2013-03-06T08:56:53.130 回答
0

无论是否发现任何异常,Try / Catch 语句的最后部分总是被触发。我建议您不要在这种情况下使用它。

try
{
  // Perform Task
}
catch (Exception x)
{
  //Handle the exception error.

}
Finally
{
  // Will Always Execute.
}
于 2013-03-06T08:56:13.600 回答