Exception Handling in Java 4

In this lesson we will conclude our discussion on exception handling in Java programming language.

There is something more to understand about the finally clause in order to use it effectively. If the finally clause includes a transfer of control statement (return, break, continue, throw) then that statement overrides any transfer of control initiated in the try or in a catch clause.

First, let's assume that the finally clause does not include any transfer of control. Here are the situations that can arise:
  • No exception occurs during execution of the try, and no transfer of control is executed in the try. In this case the finally clause executes, then the statement following the try block.
  • No exception occurs during execution of the try, but it does execute a transfer of control. In this case the finally clause executes, and then the transfer of control takes place.
  • An exception does occur during execution of the try, and there is no catch clause for that exception. Now the finally clause executes, then the uncaught exception is "passed up" to the next enclosing try block, possibly in a calling function.
  • An exception does occur during execution of the try, and there is a catch clause for that exception. The catch clause does not execute a transfer of control. In this case the catch clause executes, then the finally clause, then the statement following the try block.
  • An exception does occur during execution of the try, there is a catch clause for that exception, and the catch clause does execute a transfer of control. Here, the catch clause executes, then the finally clause, then the transfer of control takes place.

If the finally block does include a transfer of control, then that takes precedence over any transfer of control executed in the try or in an executed catch clause. So for all of the cases listed above, the finally clause would execute, then its transfer of control would take place. Here's one example:
try {
   return 0;
}
finally {
   return 2;
}
The result of executing this code is that 2 is returned. Note that this is rather confusing! The moral is that you probably do not want to include transfer-of-control statements in both the try statements and the finally clause, or in both a catch clause and the finally clause.