Catch multiple Exceptions at one go

It is not a good practice to catch System.Exception, as the catch block will be executed with unexpected exceptions and it will hide the real error. But sometimes, you want to catch multiple exceptions in order to avoid unnecessary repetitive code. For example,

try
{
    var rsponse = lginService.Login(username, password);
    Log(user.ID);
    CreateCookie(tokenResponse.TokenResponse);
    return user;
}
catch (AuthenticationException)
{
    return null;
}
catch (MultipleFailedLoginAttemptsException)
{
    return null;
}
catch (UserStatusException)
{
    return null;
}
catch (PaymentFailedException)
{
    return null;
}

In this case, you can catch System.Exception but limit the impact with if statement (http://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once)

catch (Exception ex)
{
    if (ex is AuthenticationException || 
        ex is MultipleFailedLoginAttemptsException || 
        ex is UserStatusException || 
        ex is PaymentFailedException) 
        return null;

    throw;
}

“is” statement is nice as the code reads like plain English.
Make sure you “throw”, rather than “throw ex”, as it will generate a new exception with an empty call stack. “throw” simply throws the existing exception.

Catch multiple Exceptions at one go

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s