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

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

问题描述

这是泄气简单地搭上 System.Exception的。相反,只有已知的例外应该被捕获。

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

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

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;
}

我在想:有没有办法赶上两个例外,只有致电 =的WebID Guid.Empty 调用一次

编辑:给出的例子是相当简单的,因为它只是一个 GUID 。但是想象一下,code,你修改一个对象多次,如果操作的一个出现故障按照预期的方式,你要重置的对象。但是,如果有一个意外的异常,我还是想抛出高。

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 fail in an expected way, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

关于答案:谢谢大家!出于某种原因,我曾在的switch-case 语句我的思维定势,不支持开启的GetType() 。现在,有两个答案,一个使用的typeof 一用。我首先想到 typeof运算()将是我的职责,因为我想:嘿,我只是想抓住出现FormatException ,因为这是我唯一希望。但是,这并不是多么赶上()工作:抓也捕捉所有派生的异常。经过考虑之后,这实在是显而易见的:否则,赶上(例外前)是行不通的!所以正确答案是。耶,学会了两件事,只有一个问题\ O /

About the answer: Thanks everyone! For some reason, I had my mind set on a switch-case statement which does not support switching on GetType(). Now, there were two answers, one using "typeof" and one using "is". I first thought typeof() would be my function, because I thought "Hey, I only want to catch FormatException because that's the only thing I expect". But that's not how catch() works: catch also catches all derived exceptions. After thinking about it, this is really obvious: Otherwise, catch(Exception ex) would not work! So the correct answer is "is". Yay, learned two things with only one question \o/

推荐答案

捕捉 System.Exception的和打开类型

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

    throw;
}


由于几个答案,在这个线程现在说(upvote他们也一样),因为C#六是更好的使用:


As several answers in this thread now say (upvote them as well), since C# 6 it is much better to use:

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

它之所以比较好,是我们避免介绍堆栈跟踪抛出的轻微腐败;原来(preC#6)的方式 。这真的只是赶上所需的情况。

The reason why it is better, is that we avoid the mild corruption of the stack trace introduced by throw; in the original (pre-C# 6) approach. This will really only catch the desired cases.

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

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