The finally block runs code after try and catch, no matter what happens. It helps clean up or finish tasks.
0
0
Finally block in Javascript
Introduction
You want to close a file or connection after trying to read it.
You want to stop a loading spinner after a task finishes, whether it worked or failed.
You want to reset variables or states after an operation.
You want to log that a process ended, no matter if it succeeded or threw an error.
Syntax
Javascript
try { // code that might throw an error } catch (error) { // code to handle the error } finally { // code that runs always }
The finally block runs after try and catch, even if there is no error.
If you return inside try or catch, finally still runs before the function returns.
Examples
This shows all blocks. Since no error happens,
catch is skipped but finally runs.Javascript
try { console.log('Try block runs'); } catch (e) { console.log('Catch block runs'); } finally { console.log('Finally block runs'); }
Here, an error is thrown and caught. The
finally block runs after catch.Javascript
try { throw new Error('Oops'); } catch (e) { console.log('Caught:', e.message); } finally { console.log('Always runs'); }
Even with a return in
try, finally runs before the function returns.Javascript
function test() { try { return 'From try'; } finally { console.log('Finally runs before return'); } } console.log(test());
Sample Program
This program tries to read data but throws an error. The error is caught and logged. The finally block cleans up resources no matter what.
Javascript
function readData() { try { console.log('Reading data...'); throw new Error('Failed to read'); } catch (error) { console.log('Error:', error.message); } finally { console.log('Cleaning up resources'); } } readData();
OutputSuccess
Important Notes
The finally block is useful for cleanup tasks like closing files or stopping timers.
If the finally block itself throws an error, that error will replace any previous error or return value.
Summary
The finally block always runs after try and catch.
Use it to run code that must happen no matter what, like cleanup.
It runs even if there is a return or error inside try or catch.