Ad space (banner)
🟨JavaScript Lessons
Lesson 51 / 69

Cleanup Processing with try/catch/finally

In this lesson you'll learn how to write cleanup processing with try/catch/finally, so you can write code that's guaranteed to run regardless of whether an error occurred. This is for people searching "JavaScript finally usage."

A finally block is a cleanup block that always runs, whether or not an exception occurred. It's used when you want to say "whether or not an error happens, I definitely want this one piece of processing to run at the end." Operations like closing a file, ending a network connection, or hiding a loading indicator need to run reliably no matter whether an error occurred, which is exactly where finally comes in handy.

The sample code adds, inside the divide function, a message displayed via finally, saying "finishing the calculation," on top of the calculation in try and the error handling in catch. Check that this finally message is shown both when the division succeeds and when it results in an error.

A common beginner stumbling block is the timing at which the finally block runs. Even if there's a return inside try or catch, finally runs before that value is actually returned — a slightly unusual order. When writing error handling, don't forget about finally's existence, not just catch.

finally is often used for processing that needs to reliably release a resource, like a database connection or a network request. In real development, bundling necessary cleanup — like the post-processing of a network request, or turning a loading indicator on and off — into finally, regardless of success or failure, helps avoid duplicating code.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)