Avatar
9057 reputation
Posted on:19 Aug '16 - 10:37
30

Catch multiple exceptions at once?

It is discouraged to simply catch 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? 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.

C#

Answers

35
This answer is accepted

Catch System.Exception and switch on the types

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

    throw;
}

Avatar
7718 reputation
Posted on:20 Aug '16 - 04:37

Please login in order to answer a question