next up previous contents
Next: Cleaning up with finally Up: Exception handing Previous: Exception handing   Contents

Java's try-catch blocks

Java treats an exception as an object with structure. When an error happens, an appropriate exception object is thrown back to the program that generated the error. The instance variables of this object contain information about the nature of the exception. At the very least, there is an error message stored in the object as a string.

If the program is written properly, it can catch the exception object, analyze its contents to determine the cause of the error and then take corrective action if necessary. This is known as handling the exception.

In Java, all exception objects are subclasses of a class called Throwable. There are two immediate subclasses of Throwable, called Error and Exception. The class Error covers exceptional situations that arise because of circumstances beyond the program's control--for instance, the kind of error that occurs if a file that needs to be read cannot be found on the disk. The other subclass, Exception, has one subclass RunTimeException, that captures standard runtime computational errors such as divide-by-zero and out-of-bounds-access of an array.

Java supports a try-catch structure to catch exceptions:

  try{
       ... // Code that might generate error
       ...
     }
  catch (ExceptionType1 e1){...} // Analyze contents of e1 
                                 // Corrective code for ExceptionType1

  catch (ExceptionType2 e2){...} // Analyze contents of e1
                                 // Corrective code for ExceptionType2

If an error occurs in the try block, the exception object generated is passed to the (multiple) catch statements accompanying the try block. The type of the exception object is checked sequentially against each catch statement till it matches. In the example above, if the first catch statement were to be rewritten as

  catch (Throwable e1){...}

all exception objects would match Throwable and be handled by this piece of code, ignoring the rest. One should, in general, arrange the catch statements so that the earlier statements deal with more specific exception types than later catch statements.

The sequence of flow when an exception occurs is as follows:


next up previous contents
Next: Cleaning up with finally Up: Exception handing Previous: Exception handing   Contents
Madhavan Mukund 2004-04-29