Friday, March 13, 2015

Java : The finally block

The finally block is always executed after the try block, even if an exception is thrown.

Consider the following example. Even though the catch block has a return statement, the finally block's return statement takes precedence and the method returns 3.
public static int test() {
  try {
    System.out.println("inside try");
    String str = null;

    return 1;
  catch (NullPointerException nullPointer) {
    System.out.println("inside catch");

    return 2;
  finally {
    System.out.println("inside finally");

    return 3;
The finally block is optional if there is at least one catch block.

Check out the post I did on Exception Handling in Java.
Wikipedia's "Speed of Light" article

Cay Horstman's book Big Java pages 88, 384, 568.

Java Programming : Advanced Topics (first edition) by Joe wigglesworth and Paula McMillan, pages 75, 88, 117, 154, 159, 205, 229, 233, 257.

No comments:

Post a Comment