Java Exceptions  «Prev  Next»

Lesson 7 The finally clause
Objective Use the finally clause to ensure that a section of code is executed.

Java finally Clause


finally clause in Java

You may be wondering why the finally clause is necessary in Java since memory is automatically released by the Java garbage collector.
Granted, the role of the finally clause would be to free memory if Java did not have automatic garbage collection.
However, there are other situations where cleanup needs to be performed that is not directly associated with freeing up memory.
Consider, for example, the situation of a file or network connection that must be closed regardless of whether an exception is thrown. The finally clause is very useful in this situation.
Keep in mind that the finally clause is intended to be used in conjunction with catch clauses, not in place of them. Depending on the specific needs of a particular program, you may want to employ both types of clauses to properly deal with problems associated with exceptions.
Do not lose sight of the fact that code in a finally clause is always executed regardless of any thrown exceptions.
The finally clause of a try statement provides a way to make sure that a block of code is executed regardless of how control leaves a try block. Control leaves a try block when the try block completes normally, when an exception is thrown and then caught, when an exception is thrown and not caught, or when a break, continue, or return statement is encountered. The finally clause is typically used to close files or release other resources. Following is an example of using the finally clause to make sure a line of code is executed:

void someMethod(String s) {
  try {
    int n = Integer.parseInt(s);
    System.out.println("n = " + n);
  }
  finally {
    System.out.println("finally");
  }
  System.out.println("the end");
}


If someMethod() is invoked with a string that does represent an integer, then all three println() statements will be executed.
However, if someMethod() is invoked with a string that does not represent an integer, then NumberFormatException will be thrown by parseInt().
Control will then jump to the finally block where finally will be displayed before the exception propagates up to the invoking method.

Using try statement with multi-catch and finally clauses

Prior to Java 7, if a try block needed to execute the same action for multiple exceptions thrown, it had to define separate handlers for each of them. Starting with Java 7, you can catch multiple, unrelated exceptions with one handler, also called a multi-catch.

Comparing single-catch handlers and multi-catch handlers

The multi-catch comes in handy if you need to execute the same action for handling multiple, unrelated exceptions. I specifically mention unrelated exceptions, because an exception handler for, say, MyException, can handle MyException and all of its subclasses. You can compare this approach of defining separate exception handlers (prior to Java 7) with defining only one exception handler to execute the same steps for multiple unrelated exceptions (starting in Java 7) by using figure 5-7. Now that you know the difference between a multi-catch and single-catch handler, let’s dive into the details of defining multi-catch handlers with finally clauses.

Comparing the differences between executing the same action with single-catch and multi-catch exception handlers
Figure 5-7: Comparing the differences between executing the same action with single-catch and multi-catch exception handlers


Quiz Question

What will be the result of trying to compile and run the following program?

public class Test {
  public static void main(String[] args) {
    System.out.println(Integer.parseInt("two"));
  }
}

  1. Compilation Fails
  2. 2
  3. 2.0
  4. Compilation succeeds and an IllegalArgumentException is thrown at runtime
  5. Compilation succeeds and a NumberFormatException is thrown at runtime

Answer: e

Explanation
The actual exception thrown is a Number Format Exception. Illegal Argument Exception is the super class of Number Format Exception.