Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.17 The finally Clause

cat.jpg

A try statement can optionally have a finally clause. The code in the finally clause executes whether or not an exception occurred.

Let us first look at the simplest case: a try statement with a finally clause but no catch clause:

try {
  // Acquire resources
  . . .
  // Do work
  . . .
} finally {
  // Relinquish resources
  . . .
}

The finally clause is executed in all of the following cases:

  • If all statements in the try clause completed without throwing an exception

  • If a return or break statement was executed in the try clause

  • If an exception occurred in any of the statements of the try clause

You can also have a try statement with catch and finally clauses:

try {
  . . .
} catch (e) {
  . . .
} finally {
  . . .
}

Now there is an additional pathway. If an exception occurs in the try clause, the catch clause is executed. No matter how the catch clause exits (normally or through a return/break/throw), the finally clause is executed afterwards.

The purpose of the finally clause is to have a single location for relinquishing resources (such as file handles or database connections) that were acquired in the try clause, whether or not an exception occurred.

  • + Share This
  • 🔖 Save To Your Account