一次捕获多个异常? [英] Catch multiple exceptions at once?

查看:41
本文介绍了一次捕获多个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不鼓励简单地捕获System.Exception.相反,只有已知的"应该捕获异常.

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

现在,这有时会导致不必要的重复代码,例如:

Now, this sometimes leads to unnecessary repetitive code, for example:

try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}

我想知道:有没有办法捕获两个异常并且只调用一次 WebId = Guid.Empty 调用?

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

给定的示例相当简单,因为它只是一个GUID.但是想象一下你多次修改一个对象的代码,如果其中一个操作按预期失败,你想要重置"对象.对象.但是,如果有意外的异常,我还是想把那个扔得更高.

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

推荐答案

Catch System.Exception 并开启类型

Catch System.Exception and switch on the types

catch (Exception ex)            
{                
    if (ex is FormatException || ex is OverflowException)
    {
        WebId = Guid.Empty;
        return;
    }
    
    throw;
}

这篇关于一次捕获多个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆