Quiz

What is the purpose of the `finally` block?

Topics
JavaScript

TL;DR

A finally block runs as control leaves its associated try/catch, whether that happens normally or through return, throw, break, or continue, making it useful for deterministic cleanup. Avoid returning or throwing from finally, because its completion overrides an earlier return value or error.

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. This is useful for tasks like closing files, releasing resources, or resetting states.

async function fetchData() {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/1',
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log('Fetched data:', data);
} catch (error) {
console.error('An error occurred:', error);
} finally {
console.log('Cleanup code runs here');
}
}
fetchData();
// Try creating a typo in the URL to see error handling.

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.

If finally itself returns or throws, that new completion replaces the earlier one. This can accidentally swallow errors, so cleanup code should normally finish without changing control flow.

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://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((res) => console.log(res))
.catch((error) => console.error('Fetch error:', error))
.finally(() => console.log('Fetch attempt finished'));

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

What does this code log?

function read() {
try {
return 'try';
} finally {
return 'finally';
}
}
console.log(read());