- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.17 The finally Clause
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.