c# -在finally子句中处理异常

本文关键字:处理 异常 子句 finally | 更新日期: 2023-09-27 18:02:24

标题有点误导人,但对我来说问题似乎很直接。我有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.
  }
}

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

c# -在finally子句中处理异常

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

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

在执行时间方面,

和 的区别到底是什么?
//Handle the exception

//execute the code only if exception was thrown.

我看不见。

你根本不需要finally:

try
{
  //Do some stuff
}
catch (Exception ex)
{
  //Handle the exception
  //execute the code only if exception was thrown.
}

不管是否发现异常,Try/Catch语句的Finally部分总是被触发。我建议你不要在这种情况下使用它。

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