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,

[sourcecode language="csharp"]
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;
}
[/sourcecode]

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)

[sourcecode language="csharp"]
catch (Exception ex)
{
if (ex is AuthenticationException ||
ex is MultipleFailedLoginAttemptsException ||
ex is UserStatusException ||
ex is PaymentFailedException)
return null;

throw;
}
[/sourcecode]

"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.