How to Use finally in JavaScript: Syntax and Examples
In JavaScript, the
finally block is used after try and catch blocks to run code that executes no matter what happens in the try or catch. It is useful for cleanup tasks like closing files or stopping timers, ensuring that code runs whether an error occurs or not.Syntax
The finally block follows try and optionally catch. It always runs after the try and catch blocks finish, regardless of success or error.
try: Code that might throw an error.catch: Code to handle errors if they occur.finally: Code that runs no matter what, for cleanup or final steps.
javascript
try { // code that may throw an error } catch (error) { // code to handle the error } finally { // code that always runs }
Example
This example shows how finally runs whether or not an error happens. It prints messages to show the flow.
javascript
function testFinally(value) { try { console.log('Try block starts'); if (value < 0) { throw new Error('Negative value'); } console.log('Try block ends without error'); } catch (e) { console.log('Catch block:', e.message); } finally { console.log('Finally block always runs'); } } testFinally(1); testFinally(-1);
Output
Try block starts
Try block ends without error
Finally block always runs
Try block starts
Catch block: Negative value
Finally block always runs
Common Pitfalls
One common mistake is expecting finally to change the return value or stop errors from propagating. The finally block runs after try and catch, but it does not catch errors itself unless you handle them inside it.
Also, if you return a value inside finally, it overrides any previous return from try or catch, which can cause unexpected results.
javascript
function wrongFinally() { try { return 'from try'; } finally { return 'from finally'; // overrides try's return } } console.log(wrongFinally()); // Outputs: from finally function correctFinally() { try { return 'from try'; } finally { console.log('Cleanup in finally'); } } console.log(correctFinally()); // Outputs: from try
Output
from finally
Cleanup in finally
from try
Quick Reference
Remember these points about finally:
- Always runs after
tryandcatch. - Used for cleanup tasks like closing resources.
- Does not catch errors by itself.
- Returning inside
finallyoverrides other returns.
Key Takeaways
The finally block runs code after try and catch no matter what happens.
Use finally for cleanup tasks like closing files or releasing resources.
Avoid returning values inside finally to prevent overriding other returns.
Errors not caught in catch will still propagate after finally runs.
Finally helps keep your code safe and predictable by always running important steps.