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.
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.
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.
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:
