next up previous
Next: The getMessage() method Up: Unit 10 Previous: Example

How to catch an exception

The throw statement starts a chain of method terminations that starts with the method that executes the throw statement, and goes up to the calling methods till the main() method.

If an exception is caught, the chain of exceptions that would lead to the termination of the program is interrupted.

To catch an exception, we can use the try-catch-finally construct.


The try-catch-finally construct

Syntax:

try {
  try-block
}
catch(ExceptionClass1 e) {
  catch-block
}
catch(ExceptionClass2 e) {
  catch-block
}
...
finally {
  finally-block
}

Semantics:

Catches one or more exceptions that can occur in a code fragment. The execution of the statements in the try-block is interrupted in the case where one of these statements generates an exception. If this happens, the catch clauses are evaluated in the order in which they are written, and the catch-block is executed that corresponds to the first clause for which the generated exception belongs to the specified class. Finally, the statements in the finally-block are executed.

If no statement in the try-block generates an exception, then, at the end of its execution, only the statements in finally-block are executed.

Example:

try {
   System.out.println(Integer.parseInt(br.readLine());
}
catch(IOException e1) {
   System.out.println("An IO error occurred.");
}
catch(NumberFormatException e2) {
   System.out.println("The string read does not contain an integer.");
}
finally {
   System.out.println("Block executed.");
}

This code fragment tries to convert a string read from an input channel to an integer and to print the integer. If an IO error occurs, or if the string read does not contain a sequence of digits, a corresponding error message is printed on the video. In any case, the println() statement for the string "Block executed", corresponding to the finally clause, is executed.



next up previous
Next: The getMessage() method Up: Unit 10 Previous: Example