如果我想捕获除给定类型之外的所有异常,并且这些特定类型将被重新抛出以在更高的上下文中被捕获,这样做会更好吗:
try
{
//Code that might throw an exception
}
//Catch exceptions to be handled in this context
catch (Exception ex) when (!IsExcludedException(ex))
{
//Handle leftover exceptions
}
或者这样做会更好:
try
{
//Code that might throw an exception
}
catch (SpecificException)
{
throw;
}
//Catch exceptions to be handled in this context
catch (Exception ex)
{
//Handle leftover exceptions
}
或者真的不重要?有没有更好的办法?
最佳答案
第二种方法分析起来肯定更清晰,这是我看到最多的方法。具体的捕获首先发生并且不会触发通用的捕获,但是如果您没有实现特定的捕获,您仍然有后备。此外,要处理多个特定异常,您还需要更多 !(ex is SpecificException)
检查。
关于c# - 除了给定类型 : catch and rethrow or catch when? 之外,哪个更好地捕获所有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40639150/