Catch multiple Exceptions at once?

Total Post:412

Points:2888
C# 
C#
 1823  View(s)
Ratings:
Rate this:

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

Now, this sometimes leads to unneccessary repetetive 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?

  1. Post:100

    Points:700
    Re: Catch multiple Exceptions at once?

    Hello Pravesh Singh!


    Catch System.Exception and switch on the types



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

        throw;
    }


      Modified On Mar-30-2018 03:29:12 AM

Answer