Home > DeveloperSection > Forums > Catch multiple Exceptions at once?
Pravesh Singh

Total Post:411

Points:2881
Posted on    June-13-2013 3:26 AM

 C# C# 
Ratings:


 1 Reply(s)
 1046  View(s)
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?



Vijay Shukla

Total Post:100

Points:700
Posted on    June-13-2013 6:49 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick