捕获给定类型以外的所有异常哪个更好:catch and rethrow或catch when?

Ces*_*ion 2 c# exception-handling exception

如果我想捕获给定类型以外的所有异常,并且将那些特定类型重新抛出以在更高的上下文中捕获,那么这样做会更好:

try
{
    //Code that might throw an exception
}
//Catch exceptions to be handled in this context
catch (Exception ex) when (!IsExcludedException(ex))
{
    //Handle leftover exceptions
}
Run Code Online (Sandbox Code Playgroud)

或者这样做会更好:

try
{
    //Code that might throw an exception
}
catch (SpecificException)
{
    throw;
}
//Catch exceptions to be handled in this context
catch (Exception ex)
{
    //Handle leftover exceptions
}
Run Code Online (Sandbox Code Playgroud)

还是真的不重要吗?有没有更好的办法?

Qrc*_*ack 6

第二种方法肯定是更清晰的分析方法,这是我最常看到的方法。特定的捕获首先发生,并且不会触发通用的捕获,但是如果您未实现特定的捕获,则仍然会有一个后备。同样,要处理多个特定异常,您还需要进行更多!(ex is SpecificException)检查。

  • 您看到的最多,因为另一种方式是非常新的。人们长时间无法实施 (6认同)
  • 不过,您仍然需要执行 `when (!(ex is OneSpecificException || ex is OtherSpecificException || ex is SomeOtherSpecificException)` (2认同)