问题:
It is discouraged to simply catch System.Exception
. 不建议仅捕获System.Exception
。 Instead, only the "known" exceptions should be caught. 相反,仅应捕获“已知”异常。
Now, this sometimes leads to unneccessary repetitive code, for example: 现在,这有时会导致不必要的重复代码,例如:
try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty
call once? 我想知道:有没有一种方法可以捕获两个异常,并且只调用一次WebId = Guid.Empty
?
The given example is rather simple, as it's only a GUID
. 给定的示例非常简单,因为它只是一个GUID
。 But imagine code where you modify an object multiple times, and if one of the manipulations fail in an expected way, you want to "reset" the object
. 但是,请想象一下代码中多次修改对象的情况,如果其中一种操作以预期的方式失败,则您想“重置”该object
。 However, if there is an unexpected exception, I still want to throw that higher. 但是,如果有意外的例外,我仍然想将其提高。
解决方案:
参考一: https://stackoom.com/question/ZO7/一次捕获多个异常参考二: https://oldbug.net/q/ZO7/Catch-multiple-exceptions-at-once
来源:oschina
链接:https://my.oschina.net/u/4432649/blog/4466286