Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

I found some cash lying on the road today so the tone of the article is going to be cheerful.

Updated
6 min read
Error Handling in JavaScript: Try, Catch, Finally

The Guide to JavaScript Error Handling

Engage your strongest imagination muscle here folks, and paint this on the scenario canvas: You’ve just written the most elegant, beautiful JavaScript code of your life, your entire life! You hit refresh in the browser, ready to bask in your genius, and suddenly the console turns into a sea of angry red text.

TypeError: Cannot read properties of undefined (reading 'length') ReferenceError: myAwesomeVariable is not defined

Welcome to the club! We’ve all been there. Those terrifying red messages are called Runtime Errors, and they happen when JavaScript tries to execute your code but runs into an impossible situation. There are many other such errors of similar nature.

Today, we are going to learn how to tame these errors, turn those red flags into green lights, and keep our apps running smoothly. Grab your favorite beverage(mine's chilled coffee), and let’s dive in!

What Even Are Errors in JavaScript?

In JavaScript, an error is essentially bad karma balancing out justice scales, jokes aside

An object that gets thrown when something goes wrong. When the JavaScript engine hits a snag—like trying to fetch data from a server that is down, or trying to use a variable that doesn't exist—it creates an Error object and "throws" it.

If you don't catch that thrown error, it crashes your entire script. The screen freezes, buttons stop working, and your users are left wondering if they broke the internet. They sometimes do.

Why Error Handling Matters

You might be thinking, "Why don't I just write perfect code that never breaks?" Well, my friend, because the real world is chaotic! APIs go down, users type letters into phone number fields, and Wi-Fi connections drop.

This brings us to two massive benefits of error handling:

  1. Graceful Failure: Imagine a restaurant runs out of burgers. A bad failure is the chef screaming and burning the restaurant down. A graceful failure is the waiter politely saying, "We're out of burgers, but can I offer you a pizza?" Error handling lets your app fail gracefully. Instead of a blank white screen, you can show the user a friendly popup saying, "Oops, something went wrong, please try again!"

  2. Debugging: Good error handling is like leaving a trail of breadcrumbs for your future self. Instead of spending three hours wondering why a function didn't work, a well-placed error message will tell you exactly what went wrong and where. It turns debugging from a nightmare into a breeze.

The Safety Net: try and catch

The most common way to handle unpredictable code is by using the try...catch block. It’s exactly what it sounds like: you try to do something risky, and if it blows up, you catch the explosion before it destroys your app.

Here is what it looks like in action:

const sketchyData = "{this is definitely not a valid JSON}";

try {
  //We put the risky code inside the 'try' block
  console.log("Attempting to parse the data...");
  const user = JSON.parse(sketchyData); 
  
  // If the line above fails, this next line never runs and the execution thread jumps into 'catch' block
  console.log("Success! Welcome,", user.name); 

} catch (error) {
  //If the 'try' block explodes, we end up here
  console.log("Uh oh, the data was bad!");
  console.error("Here is the exact problem:", error.message);
  
  // Graceful failure: Set a default user instead of crashing
  const user = { name: "Guest" }; 
}

Try and Catch have saved countless dev lives in production. I have learnt that no harm comes from implementing try & catch blocks.

The finally Block

Sometimes, you need to do some cleanup regardless of whether your code succeeded or failed. Did you turn on a loading spinner? You need to turn it off. Did you open a database connection? You need to close it.

Enter the finally block. This block of code runs no matter what happens in the try or catch emphasis on no matter what. It’s the reliable janitor of JavaScript.

let isLoading = true;

try {
  console.log("Fetching user profile...");
  // Imagine an error happens here
  throw new Error("No internet connection!");
} catch (error) {
  console.log("Failed to fetch profile:", error.message);
} finally {
  // This runs whether the fetch was a success OR a failure
  isLoading = false;
  console.log("Loading spinner turned off. We are done here.");
}

Throwing Custom Errors

Sometimes JavaScript thinks everything is fine, but you know it’s not. For example, JavaScript is perfectly happy to let a user enter "-5" as their age, but your business logic knows time travel isn't real.

You can take control and throw your own errors using throw new Error().

function processUserAge(age) {
  try {
    if (age < 0) {
      // We are creating and throwing our own custom error
      throw new Error("Age cannot be a negative number!");
    }
    if (typeof age !== "number") {
      throw new TypeError("Age must be a number, not a string!");
    }
    
    console.log(`User is ${age} years old. Proceeding...`);
    
  } catch (error) {
    // We catch our own custom errors right here
    console.warn("Input Validation Failed:", error.message);
  }
}

processUserAge(-5); // Triggers the negative number error
processUserAge("twenty"); // Triggers the type error
processUserAge(25); // Succeeds perfectly

Suggestions for Masterful Error Handling

To wrap things up, here are a few pro-tips to take your error handling from good to great:

  • Don't swallow errors! Never write a catch block that is completely empty. If you catch an error and do nothing, the app will fail silently, and you'll spend hours tearing your hair out trying to find the bug. At the very least, console.error(error) it!

  • Use the right console method: Use console.log() for general info, console.warn() for things that are weird but not fatal, and console.error() for actual failures. It makes reading your browser console much easier. Pure syntactical sugar.

  • Trust the process: Getting errors doesn't mean you are a bad developer. It means you are a developer! Embrace the red text, read the error messages carefully (they usually tell you the exact line number), and use try...catch to keep your users happy.

Conclusion

Try Catch is utterly important for any developer, and if you have already learnt try and catch then why leave finally.

Happy coding, and may all your failures be graceful!