Search code examples
c#.netexception

Catch multiple exceptions at once?


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

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

Is there a way to catch both exceptions and only set WebId = Guid.Empty 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 fails as expected, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.


Solution

  • Catch System.Exception and switch on the types

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