What is the purpose of the `finally` block?
TL;DR
The finally
block in JavaScript is used to execute code after a try
and catch
block, regardless of whether an error was thrown or caught. It ensures that certain cleanup or finalization code runs no matter what. For example:
try {// Code that may throw an error} catch (error) {// Code to handle the error} finally {// Code that will always run}
Purpose of the finally
block
Ensuring cleanup
The finally
block is often used to ensure that certain cleanup code runs regardless of whether an error occurred or not. This is useful for tasks like closing files, releasing resources, or resetting states.
try {// Attempt to execute code that may throw an errorlet data = fetchData();} catch (error) {// Handle any errors that occurconsole.error('An error occurred:', error);} finally {// Always execute this codeconsole.log('Cleanup code runs here');}
Guaranteeing execution
The finally
block guarantees that the code within it will execute after the try
and catch
blocks have finished. This is true even if a return
statement is encountered in the try
or catch
blocks.
function exampleFunction() {try {return 'Try block';} catch (error) {return 'Catch block';} finally {console.log('Finally block');}}console.log(exampleFunction()); // Output: 'Finally block' followed by 'Try block'
Handling asynchronous code
When dealing with asynchronous code, the finally
block can be used to ensure that certain actions are taken after a promise is settled, regardless of its outcome.
fetch('https://api.example.com/data').then((response) => response.json()).catch((error) => console.error('Fetch error:', error)).finally(() => console.log('Fetch attempt finished'));