3.1.5 Catching Multiple Exception Types3.1.4 Handling Exceptions3.1 Exception Handling3.1.6 The finally Clause

3.1.5 Catching Multiple Exception Types

If multiple types of exceptions have a common supertype, it is not necessary to have an individual handler for each of these exceptions. Rather there may be a generic handler which catches all instances of this supertype. Since every exception is a subtype of Exception, we may thus catch all kinds of exceptions by a single handler:

   try
   {
     // may raise multiple kinds of exceptions
     ... 
   }
   catch(Exception e)
   {
     // catches all possible kinds of exceptions
     ...
   }

This is useful if all different exceptions are handled by the same recovery mechanism, e.g., by printing an error message and returning a special value to the caller of the method.  

If a try block has multiple exception handlers, the handlers are tried in sequence when an exception is thrown. We may therefore catch some exceptions by more specific handlers and have a "default handler" at the end catching all other exceptions:

   try
   {
     // may raise multiple kinds of exceptions
     ... 
   }
   catch(ExceptionClass1 e)
   {
     // catches exception type 1
     ...
   }
   catch(Exception e)
   {
     // catches all other kinds of exceptions
     ...
   }


© Wolfgang Schreiner; February 3, 2005

3.1.5 Catching Multiple Exception Types3.1.4 Handling Exceptions3.1 Exception Handling3.1.6 The finally Clause