finally and Cleanup

A finally block executes after the try/catch path regardless of whether the operation succeeds or throws, making it useful for cleanup. Be careful when returning from finally: a return there can override a return or exception from the try/catch block.

Resource Cleanup
let connection;

try {
  connection = openConnection();
  useConnection(connection);
} catch (error) {
  console.error(error);
} finally {
  connection?.close();
}
💡 The finally block provides a reliable place to perform cleanup regardless of success or failure.
Key Takeaways
  • finally is designed for cleanup.
  • Cleanup should happen even when an exception occurs.
  • Avoid returning from finally unless you intentionally want to override control flow.
Knowledge Check

When is finally useful?