Topic Introduction

Welcome back! After exploring the try and catch blocks in JavaScript, we're now moving on to the finally block, a companion of the try and catch blocks, performing the necessary cleanup. Today, we'll explore its application.

Unveiling the Finally Block

The finally block is a section of code that always executes after the try and catch blocks, running irrespective of whether an exception occurred. This block executes no matter if the exception has happened or not. Curious? Let's take a look:

This is the basic structure of the try/catch/finally block. See - no matter what's inside try and catch, the content of the finally block will be executed after them, allowing you to proceed with some cleanup or post-actions!

Let's look into finally applications in more detail.

Why and When It's Finally Time

The finally block handles activities that are either risky or not after the try and catch blocks have been executed. Whether your try block throws an exception or not, it doesn't matter — the finally block ensures necessary tasks are completed. For example, when interacting with a database, you must close the connection. This is done with finally:

While this example might not be something you face right away, it's important to understand the appliance of the finally block in real life.

Handling Finally with Examples

Let's dive into action. In this example, the finally block executes and logs "Finally!" to the console, regardless of the exception:

Even in the absence of exceptions, the finally block still runs:

Lesson Summary: Finally Block, Mastered!

Great work! We've mastered the finally block, the dependable cleanup tool for your JavaScript code that executes after try and catch blocks, regardless of exceptions. Excellent job!

Are you ready for practice to reinforce your knowledge? Up next, get hands-on to solidify these concepts. Let's dive deeper into the JavaScript cosmos!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal