Catch multiple exceptions at once: C#

The try{} block contains set of statements where an exception can occur. A try block is always followed by a catch{} block , which handles the exception that occurs in associated try block. In some situations, a single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. But, this sometimes leads to unnecessary repetitive code :


How to Catch multiple types of exceptions in one catch block
example
try
{
  // try some stuff
}
catch (FormatException ex)
{
  HandleIt(ex);
}
catch (OverflowException ex)
{
  HandleIt(ex);
}
catch(Exception)
{
  throw;
}

In the above example there is some code duplication and it is better to avoid while catching exception.

Switch on the types

You can avoid this code duplication by catch System.Exception and handle the specific types; otherwise, throw the exception to be handled higher up in the code:

catch (Exception ex)
{
  if (ex is FormatException  ex is OverflowException)
  {
    // write to a log, whatever...
    return;
  }
  throw;
}

C# Exception filters


C# Exception Handling Best Practices using Exception filters

Using catch arguments is one way to filter for the exceptions you want to handle. You can also use an exception filter that further examines the exception to decide whether to handle it. An Exception Filter is a new feature of C# 6.0 . These Filters are clauses that determine when a given catch clause should be applied or not. If the expression used for an exception filter return true, the catch clause performs its normal processing. If the expression return false, then the catch clause is skipped. So, we can write a catch{} block that will handle the exception only when a certain condition is true that is written in an exception filter clause.

Syntax
catch (ArgumentException e) when (e.ParamName == "…")
{
}
example
try
{
  // try some stuff
}
catch (MyException ex) when (ex.Code == 403)
{
  HandleException(ex);
}

Here the catch block will be entered if and only if ex.Code == 403. If the condition is not verified, the exception will bubble up the stack until it's caught somewhere else or terminates the process .

Thus, if we want to handle multiple types of exceptions in the same way using Exception Filters , we could write this:

try
{
  // try some stuff
}
catch(MyException ex) when(ex.Code == 403  ex.Code == 404)
{
  HandleException(ex);
}

A common use of exception filter expressions is logging. You can create a filter that always evaluate false that also outputs to a log, you can log exceptions as they go by without having to handle them and rethrow.



NEXT.....using statement in C#