Skip to content

finally

In JavaScript, the finally keyword starts the clause of a try statement that always runs when control leaves the try block, whether the block finished normally, threw an exception, or exited early with return, break, or continue. It comes last, after the try block and after the catch clause when there is one.

In a try...finally statement without catch, an exception still propagates once the finally block finishes. A return in the try block evaluates its value first, then finally runs, and only then does the function return. A return or throw inside finally replaces whatever the earlier blocks were about to do, which can silently discard an exception.

For objects that know how to release themselves, the using declaration runs the same kind of cleanup automatically.

JavaScript finally Keyword Syntax

A finally block comes last in a try statement, with or without a catch block:

Language: JavaScript Syntax
try {
  <statements>
} [catch [(<binding>)] {
  <statements>
}] finally {
  <statements>
}

JavaScript finally Keyword Examples

A finally block runs whether the try block returns normally or throws:

Language: JavaScript
> function divide(a, b) {
…   try {
…     if (b === 0) {
…       throw new RangeError("Division by zero");
…     }
…     return a / b;
…   } finally {
…     console.log("Done");
…   }
… }
undefined

> divide(10, 4)
Done
2.5

> try {
…   divide(1, 0);
… } catch (error) {
…   console.log(error.message);
… }
Done
Division by zero
undefined

The finally block runs before the function returns 2.5, and again before the RangeError leaves the function and reaches the outer catch block.

A return inside finally overrides the return in the try block:

Language: JavaScript
> function getStatus() {
…   try {
…     return "from try";
…   } finally {
…     return "from finally";
…   }
… }
undefined

> getStatus()
'from finally'

The call returns "from finally", and the "from try" value from the try block is discarded.

JavaScript finally Keyword Use Cases

  • Releasing resources such as file handles, locks, or connections
  • Resetting state, such as a loading flag, after an operation succeeds or fails
  • Logging that an operation ended, whatever its outcome

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 5, 2026