0
0
Javascriptprogramming~3 mins

Why Finally block in Javascript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your cleanup code never got skipped, no matter what errors happen?

The Scenario

Imagine you are writing code that reads a file and then closes it. If you forget to close the file after reading, it can cause problems like memory leaks or locked files.

Doing this manually means you have to remember to close the file every time, even if an error happens while reading.

The Problem

Manually closing resources is slow and easy to forget. If an error occurs, your code might skip the closing step, causing bugs that are hard to find.

This makes your program unreliable and can crash or behave unexpectedly.

The Solution

The finally block runs code no matter what happens before it. Whether an error occurs or not, the code inside finally always executes.

This means you can put cleanup tasks like closing files or releasing resources there, making your code safer and cleaner.

Before vs After
Before
try {
  readFile();
  closeFile();
} catch (e) {
  handleError(e);
  closeFile();
}
After
try {
  readFile();
} catch (e) {
  handleError(e);
} finally {
  closeFile();
}
What It Enables

It lets you guarantee important cleanup actions happen, keeping your programs stable and error-free.

Real Life Example

When downloading a file from the internet, you want to always close the connection, even if the download fails. The finally block ensures the connection closes no matter what.

Key Takeaways

finally runs code always, even after errors.

It helps clean up resources safely.

Makes your programs more reliable and easier to maintain.