CATCH MULTIPLE EXCEPTIONS AT ONCE?

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C# 
C#
 1491  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. Vijay Shukla

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!