CKTIS / JavaScript
finally — the concluding block of a try statement
The finally keyword introduces a block executed after try and any catch, before control continues elsewhere. It supports cleanup even during a return or exception, but can itself override the earlier outcome.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
try {
// statements
} finally {
// cleanup
}
try {
// statements
} catch (error) {
// error handling
} finally {
// cleanup
}finally is a reserved keyword introducing the concluding block of a try statement. Valid forms are try…finally and try…catch…finally; standalone finally is invalid. Braces are required, and catch is optional when finally is present.
When execution leaves try and any catch, the finally block runs first: after normal completion and during a return, exception, break, or continue. Use it for cleanup that must happen before control continues elsewhere. This does not guarantee execution after process termination or when earlier code never finishes.
If finally completes normally, the earlier control-flow outcome is preserved. A return, throw, or contextually valid break or continue leaving finally overrides that outcome; it can therefore hide an exception or change a returned value. Avoid such statements in cleanup code. An exception thrown by finally is not handled by the catch belonging to the same try statement.
In the example, the value "done" is evaluated before cleanup, but task() returns it only after appending "cleanup".
Examples
function run() {
const events = [];
function task() {
try {
events.push("work");
return "done";
} finally {
events.push("cleanup");
}
}
const result = task();
return events.join(" -> ") + " | " + result;
}
console.log(run());Result
work -> cleanup | done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.