Chapter XXIII · Error Handling
finally
The `finally` statement defines a cleanup code block that executes regardless of whether an error was thrown or caught.
01 How It Works
Think of turning off workshop lights and locking doors at the end of every working day regardless of events.
The `finally` block guarantees execution after `try` and `catch` blocks complete, making it ideal for resource cleanup.
example.js
let db = openConnection();
try {
db.query();
} catch (err) {
console.log("Query failed");
} finally {
db.close(); // Always cleans up
}
1. Execute `try` and optional `catch` logic.
2. Trigger `finally` block unconditionally.
3. Release network connections, file streams, or loaders.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
try {
console.log("Running task");
} finally {
console.log("Cleanup executed unconditionally");
}
Key Takeaway
Use `finally` blocks to guarantee essential cleanup tasks execute under all circumstances.