Java - Exception finally Block

Introduction

A try block can also have zero or one finally block.

A finally block is never used by itself.

It is always used with a try block.

A finally block is guaranteed to be executed no matter what happens in the associated try and/or catch block.

There are two exceptions to this rule:

  • If the thread that is executing the try or catch block dies, or
  • A Java application may exit, for example, by calling System.exit() method, while executing the try or catch block.

Syntax

The syntax for using a finally block is

finally {
        // Code for finally block goes here
}

There are two possible combinations of try, catch, and finally blocks: try-catch-finally or try-finally.

A try block may be followed by zero or more catch blocks.

A try block can have a maximum of one finally block.

A try block must have either a catch block, a finally block, or both.

The syntax for a try-catch-finally block is

try {
        // Code for try block goes here
}
catch(Exception1 e1) {
        // Code for catch block goes here
}
finally {
        // Code for finally block goes here
}

The syntax for a try-finally block is

try {
        // Code for try block goes here
}
finally {
        // Code for finally block goes here
}

Related Topics