What does the finally block do?
The finally block in a try...catch...finally construct is part of the error-handling mechanism,
which is used to run code no matter what - regardless of whether an error occurred.
Short answer
finallyruns always, aftertryandcatch, even iftryhad an error, athrowfired, or the function did areturn.
Syntax
try {
// code that can throw an error
} catch (error) {
// error handling
} finally {
// code that runs no matter what
}How it works step by step
- The code in
tryruns. - If
tryhas no error →catchis skipped →finallyruns. - If
tryhas an error →catchruns → thenfinally. - After
finally, program execution continues.
Example 1. No error - finally still runs
try {
console.log("try: all good");
} catch (e) {
console.log("catch: error");
} finally {
console.log("finally: always runs");
}Output:
try: all good
finally: always runsExample 2. There is an error - finally runs too
try {
throw new Error("Error!");
} catch (e) {
console.log("catch:", e.message);
} finally {
console.log("finally: always runs");
}Output:
catch: Error!
finally: always runsExample 3. finally runs even with a return
function test() {
try {
console.log("try");
return "From try";
} catch {
console.log("catch");
} finally {
console.log("finally");
}
}
console.log("Result:", test());Output:
try
finally
Result: From tryEven if
trydid areturn, thefinallyblock still runs before the function exits.
Example 4. finally runs on throw
try {
throw new Error("Error!");
} catch (e) {
console.log("catch:", e.message);
} finally {
console.log("finally runs no matter what");
}Output:
catch: Error!
finally runs no matter whatExample 5. finally runs even if catch errors
try {
throw new Error("Error in try");
} catch (e) {
console.log("catch:", e.message);
throw new Error("Error in catch");
} finally {
console.log("finally still runs");
}Output:
catch: Error in try
finally still runs
Uncaught Error: Error in catchEven if
catchthrows again -finallystill runs.
Example 6. finally can change what return does
If finally has a return, it overwrites the result from try or catch:
function test() {
try {
return "From try";
} finally {
return "From finally";
}
}
console.log(test()); // "From finally"This is considered bad practice, because it makes the function's behavior unpredictable.
Main uses
Releasing resources:
try {
openConnection();
executeQuery();
} catch (e) {
console.error("Error:", e);
} finally {
closeConnection(); // always runs
}Cleaning up temporary data Releasing locks Finishing operations regardless of the outcome
Summary
| Block | When it runs | Purpose |
|---|---|---|
try | Always | The code where an error can occur |
catch | Only on error | Exception handling |
finally | Always | Cleanup, wrap-up, releasing resources |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.