Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: A Simple Guide to Try, Catch, and Finally

Stop your code from breaking and learn how to handle mistakes gracefully.

Updated
5 min read
Error Handling in JavaScript: A Simple Guide to Try, Catch, and Finally
A

Full-stack developer and startup founder building tech solutions in Ayodhya. Vlogger with 27k+ followers sharing my journey in technology and SaaS.

Have you ever written a piece of JavaScript, refreshed your browser, and... nothing happened? You open the developer console and see a big, scary red error message.

If this has happened to you, do not worry! Errors happen to every developer, no matter how much experience they have. The important part is not being perfect; the important part is knowing how to handle those errors when they pop up.

Today, we are going to learn how to keep our JavaScript code running smoothly using try, catch, and finally.

What Are Errors in JavaScript?

Imagine you are following a recipe to bake a cake, but the recipe asks you to add an ingredient you do not have in your kitchen. What do you do? You stop baking.

JavaScript acts the exact same way. When it reads your code from top to bottom and finds a problem, it completely stops running. We call this a runtime error because it happens while the code is actively running.

Here is a common example of a runtime error:

// We are trying to use a variable that does not exist!
console.log(mySecretMessage); 

// The script crashes here. 
// This next line will NEVER run:
console.log("Welcome to my website!");

Why Error Handling Matters

If your code crashes, your user might be left staring at a frozen screen or a broken button.

Good error handling allows for graceful failure. This means that even if a small piece of your code breaks, the rest of the website keeps working, and you can show the user a friendly message like, "Oops, something went wrong. Please try again."

It also makes debugging (finding and fixing bugs) much easier for you, because you can log exactly what went wrong!

The Rescue Team: try and catch

To stop JavaScript from crashing, we use a safety net called a try...catch block.

It works like a trapeze artist at a circus.

  1. try: JavaScript tries to do the dangerous trick (the code).

  2. catch: If the trick fails and JavaScript falls, the catch block acts as a safety net to catch the error so the show can go on!

Here is how it looks in code:

try {
  // 1. Try to run this code
  console.log("Trying to read the secret message...");
  console.log(mySecretMessage); // Uh oh! This variable doesn't exist!
  
} catch (error) {
  // 2. If it breaks, catch the error here!
  console.log("Oh no, we caught an error!");
  console.dir(error.message); // Tells us: "mySecretMessage is not defined"
}

// 3. The script survives! This will still run:
console.log("The website is still working fine.");

The Always-There Friend: finally

Sometimes, you have a piece of code that you want to run no matter what happens. Whether the try was successful or it fell into the catch net, you still need to finish up your task.

This is what the finally block is for. It always runs at the very end.

A great real-world example is a "Loading" spinner on a website. When you try to get data, you show the spinner. When you are done (whether you got the data or an error happened), you need to hide the spinner!

try {
  console.log("Fetching data from the internet...");
  // Imagine an error happens here
} catch (error) {
  console.log("Could not get the data.");
} finally {
  // This runs no matter what!
  console.log("Hiding the loading spinner.");
}

Diagram: Execution Order Flow

           [ Start Code ]
                 |
                 v
           [ try block ]
                 |
      Did an error happen?
         /               \
      YES                 NO
       |                   |
[ catch block ]            |
       |                   |
        \                 /
         v               v
         [ finally block ]
                 |
                 v
     [ Continue Rest of Code ]

Throwing Your Own Errors

Sometimes, JavaScript thinks the code is totally fine, but you know it is wrong.

For example, imagine a user is trying to sign up for your website, but they leave the email box blank. JavaScript won't crash, but you still want to stop them. You can use the throw keyword to create your very own error!

function checkAge(age) {
  try {
    if (age < 18) {
      // We are forcing an error to happen on purpose!
      throw new Error("You are too young to enter this site.");
    }
    console.log("Welcome to the site!");
    
  } catch (error) {
    // Our custom error is caught right here
    console.log("Error:", error.message);
  }
}

checkAge(15); 
// Output: Error: You are too young to enter this site.

By "throwing" an error, you immediately stop the try block and jump straight into the catch block. It is a great way to protect your app from bad data!

Conclusion

Errors are not your enemy; they are just part of writing code. By using try, catch, and finally, you can protect your users from broken screens, make your code much safer, and make your own life as a developer much easier.