Guaranteeing Execution of Code - The finally Block

Contact Us or call 1-877-932-8228
Guaranteeing Execution of Code - The finally Block

Guaranteeing Execution of Code - The finally Block

To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try ... catch blocks.

The code in the finally block will almost always execute.

  • If an exception causes a catch block to execute, the finally block will be executed after the catch block.
  • If an uncaught exception occurs, the finally block executes, and then execution exits this method and the exception is thrown to the method that called this method.
  • If either the try block or a catch block executes a return statement, the finally block executes before we leave the method.
  • If either the try block or a catch block calls System.exit, the finally block will not execute.
  • For the sake of completeness, if a finally block executes a return while an uncaught exception is pending, the exception is stifled; that is, it just disappears.
try {
	risky code block
}
catch (ExceptionClassName exceptionObjectName) {
	code to resolve problem
}
finally {
	code that will always execute
}

In summary, note the following:

  • A try block is followed by zero or more catch blocks.
    • If the catch block exception classes caught are related, the blocks must be listed in inheritance order from most derived to most basic.
  • There may one finally block as the last block in the structure.
  • There must be at least one block from the combined set of catch and finally after the try.

It's possible to have a try block followed by a finally block, with no catch block. This is used to prevent an unchecked exception, or an exception the method declared it throws, from exiting the method before cleanup code can be executed.

Code Sample:

Java-Exceptions/Demos/FinallyTest.java
import util.KeyboardReader;

public class FinallyTest {
  public static void main(String[] args) {
    System.out.println("Returned value is " + go());
  }
  
  public static int go() {
    int choice = 0;
    try {
      String name = KeyboardReader.getPromptedString("Enter your name: ");
      System.out.println("MENU:");
      System.out.println("1 - normal execution");
      System.out.println("2 - uncaught ArithmeticException");
      System.out.println("3 - return from try block");
      System.out.println("4 - call System.exit");
      System.out.println(
            "5 - return 5 from finally after ArithmeticException");
      System.out.println(
            "6 - return 6 from finally after try returns -1");
      System.out.println("X - catch NumberFormatException");
      choice = KeyboardReader.getPromptedInt("Enter your choice: ");

      if (choice == 1) System.out.println("Hello " + name);
      else if (choice == 2) System.out.println("1 / 0 =  " + 1/0);
      else if (choice == 3) return 3;
      else if (choice == 4) System.exit(1);
      else if (choice == 5) System.out.println("1 / 0 =  " + 1/0);
      else if (choice == 6) return -1;
    }
    catch (NumberFormatException e) {
      System.out.println("Number Format Exception occurred");
    }
    finally {
      System.out.println("Goodbye from finally block");
      if (choice == 5) return 5;
      if (choice == 6) return 6;
    }
    return 0;
  } 
}

The program shows a menu of possible execution paths you can trigger. The "Goodbye from finally block " message will always appear except from an explicit call to System.exit in the try block:

  • When no exception occurs, the finally block will execute after the try.
  • If an uncaught exceptions occurs, like when we divide by zero, the finally block will execute before we are thrown out of the method.
  • If we execute a return from the try block, the finally block still executes before we leave.
  • Catching a NumberFormatException is still followed by executing the finally block.
  • But, calling System.exit in the try block causes the JVM to shut down without executing the finally block.
  • When we force an uncaught exception but return from the finally block, we do not get a stack trace, indicating that the ArithmeticException just disappeared (compare choices 2 and 5).
  • When both the try block and the finally block execute a return statement, the value from the finally block is the one actually returned.
Next