The finally Block

The finally Block

finally {
    if (out != null) { 
        System.out.println("Closing PrintWriter");
    } else { 
        System.out.println("PrintWriter not open");
  • The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
  • Finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
  • Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Related concepts

The finally Block — Structure map

Clickable & Draggable!

The finally Block — Related pages: