What is the purpose of the `finally` block?
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.
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.
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.
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.