«^»
9.1. What is exception handling?

A method often detects situations which it knows it cannot handle. It may be that the arguments for the method were inappropriate; it may be that a series of calculations has led to a situation that should not occur; it may be that its attempt to allocate space using new has failed; and so on. What should the programmer of this method do when such untoward events (exceptions) arise?

The method could output an error message and then terminate execution. However, the user of the method might be extremely unhappy if this happens: he/she might want to do some ‘cleanup’ code before the program terminates.

Instead, the programmer of the method could return some value that signifies that an error has occurred. However, returning an error value may be inconvenient to the user of the method as the point of call of the method may not be the best place to handle the error. So his/her code has to be littered with error-handling code.

Some programming languages allow the code of the method to signify that an exception has occurred and this is then handled by some code that occurs elsewhere in the program. In Java, a try statement consists of a try block together with zero or more exception handlers (each introduced by the keyword catch) and an optional finally clause:

0675: try {
0676:    ...
0677: }
0678: catch( ... ) {
0679:    ...
0680: }
0681: catch( ... ) {
0682:    ...
0683: }
0684: finally {
0685:    ...
0686: }

A try statement can be used to indicate that a piece of code wishes to handle exceptions. In the code executed by the try block, a throw statement is used to signify that an exception has occurred. When a throw statement is executed, control is transferred to the exception handler of the most recently entered try statement containing an appropriate exception handler. It is possible to write an exception handler that handles all exceptions, and to write one that re-throws an exception.

How does a try statement end? If an exception occurs, the last-statement-to-be-executed will be in an exception handler; otherwise, it will be in the try block. The last-statement-to-be-executed may be a statement that causes a transfer of control (such as a return, continue or a break statement) or it may the statement that appears at the end of the exception handler or the try block. If a try statement has a finally clause, the statements of the finally clause will then be executed. If the last-statement-to-be-executed is one that causes a transfer of control, the finally clause will be executed before control is actually transferred to its new destination. So, if a try statement has a finally clause, it will always be executed.

Because a finally clause provides a way of guaranteeing that some code will be executed before a block is left, it is sometimes useful to write try statements that have a finally clause but do not have any exception handlers.