Mar 09 2010

Catching multiple Exceptions in a single block

Category: Exception HandlingMike Lovell @ 11:19 am

Don’t you hate writing multiple catch blocks which duplicate code? There’s a quick way around this by using the “is” statement.

   1:  // Author: Mike Lovell (mike.lovell@gotinker.com)
   2:   
   3:  try
   4:  {
   5:      // Code
   6:  }
   7:  catch (Exception e)
   8:  {
   9:      if (
  10:              e is OverflowException
  11:              || e is ArgumentNullException
  12:              || e is IndexOutOfRangeException
  13:          )
  14:      {
  15:          // Some other handling
  16:      }
  17:      else
  18:      {
  19:          throw;
  20:      }
  21:  }

Problem solved!

Tags: , , ,

Leave a Reply