一次捕获多个异常?

假装没事ソ 提交于 2020-08-05 10:25:26

问题:

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!