3.1.2 Exceptions3.1.1 Error Codes3.1 Exception Handling3.1.3 Example

3.1.2 Exceptions

The Java mechanism of  exceptions is based on three concepts:

  1. A protected code block: a code block can be protected from the occurrence of errors. If an error occurs during the execution of the code block, the error will be handled.
  2. An exception handler: an  exception handler is a code block that handles a particular error. Each protected code block has one ore more exception handlers that cover errors that may occur in the block.
  3. An exception: an error is signaled by triggering an exception which is an object that identifies the error. The exception is forwarded to an exception handler which deals with the error. After the exception has been handled, execution proceeds after the protected code block.

The Java construct for triggering an exception is the throw statement which is typically invoked as 

   throw new ExceptionClass(...)

This construct triggers an exception, i.e., it constructs an object of type ExceptionClass and aborts the normal execution. The exception is forwarded to the handler which is currently in charge of this exception. The class ExceptionClass must be a subclass of the Java standard class Exception.  

The Java language construct for handling exceptions is the try statement which looks in its minimal form as follows:  

   try
   {
     // protected code block
     ... 
   }
   catch (ExceptionClass e)
   {
     // exception handler, takes e as parameter
     ... 
   }

If an exception is thrown during the execution the protected code block, the execution of the protected code block is aborted. If the exception is of type ExceptionClass, it is handled by the exception handler to which the exception object is passed as a parameter. After the execution of the handler, normal execution continues with the first statement after the whole construct. If the exception is of a different type, the exception must be handled by another handler (see later).

Any method that may throw an exception has to be declared with a throws clause as in  

   type method(...) throws ExceptionClass, ...
   {
     ...
   }

i.e., all the types of exceptions that the method may throw have to be listed in the method header.


© Wolfgang Schreiner; February 3, 2005

3.1.2 Exceptions3.1.1 Error Codes3.1 Exception Handling3.1.3 Example