3.1.4 Handling Exceptions3.1.3 Example3.1 Exception Handling3.1.5 Catching Multiple Exception Types

3.1.4 Handling Exceptions

In general, a try statement may have arbitrarily many exception handlers:  

   try
   {
     ... // protected code block
   }
   catch (ExceptionClass1 e1)
   {
     ... // exception handler 1
   }
   catch (ExceptionClass2 e2)
   {
     ... // exception handler 1
   }
   ...

If in the protected code block an exception is thrown, the corresponding exception handler is selected and executed. If there is no appropriate exception handler declared, the exception is propagated to the caller of the current method. For a more detailed explanation of this question, see the following figure:


Searching

Searching for an Exception Handler
 


 

Here method m1 calls in a protected code block m2 which in turn calls m3. In the protected code block of m3, exceptions of type E1 and of type E2 may be thrown. Exceptions of type E2 are caught by the handler in m3 but exceptions of type E1 are propagated to the caller m2. m2 however does not handle any exceptions; the exception is therefore propagated to m1 where it is ultimately caught by a handler.

This figure also demonstrates another important principle; if a method m calls another method n that may throw an exception,

We will see that runtime exceptions are exempted from this rule.
m has two possibilities:
  1. m catches the exception by a corresponding handler, i.e., it must call n within a try statement.
  2. m propagates the exception to its caller, i.e., it must declare the exception type in its method header.

In above example, the body of m3 may throw exceptions of type E1 and E2; it only handles E2 and must therefore declare E1 in its header. Method m2 calls m1 which may throw exceptions of type E1; since m2 does not handle this exception, it must declare E1 in its header. Method m1 calls m2 which may throw exceptions of type E1; m1 handles this type of exception and must therefore not declare any exception type in its header.

If the main method throws an exception, this exception is caught by the JVM interpreter.


© Wolfgang Schreiner; February 3, 2005

3.1.4 Handling Exceptions3.1.3 Example3.1 Exception Handling3.1.5 Catching Multiple Exception Types