Topic 74 of 87
finally Block
Overview
The finally block is an optional addition to try...catch.
The code inside the finally block is absolutely guaranteed to execute regardless of the outcome. It runs if the try block succeeds, AND it runs if the catch block catches an error.
It is used exclusively for "cleanup" operations.
Syntax
The finally Block
javascript
// UI Loading State Starts
let isLoading = true;
try {
// Attempt network request
const data = JSON.parse("invalid-json!");
console.log("Success");
} catch (err) {
console.error("Failed to parse data");
} finally {
// This runs NO MATTER WHAT!
// Perfect for hiding loading spinners
isLoading = false;
console.log("Cleanup complete.");
}Common Pitfalls
- Placing cleanup code just randomly below the
try...catchinstead of in afinallyblock. If thecatchblock itself throws an error or contains areturnstatement, the code below thecatchwill never run! Thefinallyblock guarantees execution even if thecatchreturns early.
Interview Questions
Q:
If there is a
return statement inside the try block, does the finally block still execute?A:
Yes! This is the magic of finally. The JavaScript engine pauses the return execution, runs the finally block, and then completes the return.
Real-World Example
Closing a database connection. Whether the database query was successful or threw an error, you MUST close the connection to prevent memory leaks.
example
javascript
try {
await db.query(sql);
} catch(e) {
logError(e);
} finally {
db.closeConnection();
}Check Your Knowledge
Test your understanding of finally Block with these quick questions.