try-catch-finally Structure

Purpose:

To "try" code that may generate and exception and "catch" that exception.

Mechanics:

try {
/* Statements which may throw an exception */
}
catch(&ltThrowable 1> <exception handler 1>) {
/* Statements to do if an exeption of type Throwable 1 is thrown */
}
catch(&ltThrowable 2> <exception handler 2>) {
/* Statements to do if an exeption of type Throwable 2 is thrown */
}
catch(&ltThrowable n> <exception handler n>) {
/* Statements to do if an exeption of type Throwable n is thrown */
}
finally {
/* Statements to do regardless of whether or not an exception is thrown. */
}

Example:

try {
/* Some code that may throw a ClassCastException or a NullPointerException */
}
catch (ClassCastException c) {
/* Statements to do if a ClassCastException is thrown */
}
catch (NullPointerException n) {
/* Statements to do if a NullPointerException is thrown */
}
finally {
/* Statements to do regardless of whether or not an exception is thrown. */
}

Usage:

  • <Throwable> must be of the class Throwable or one of its subclasses.
  • <exception handler> is any valid identifier name and is the variable where the exception is stored.

Restrictions:

The programmer encloses in a try block the code that may generate an exception. The try block is immediately followed by one or more catch blocks. Each catch block specifies the type of exception it can catch and contains and exception handler. After the last catch block, an optional finally block provides code that always executes regardless of whether or not an exception occurs.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu