Michael Stum Michael Stum - 2 months ago 15
C# Question

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.

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/

Answer

Catch System.Exception and switch on the types

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

    throw;
}

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

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.