Skip to main content

Command Palette

Search for a command to run...

Error Handling in JS: Try, Catch, Finally

Updated
2 min read
Error Handling in JS: Try, Catch, Finally

What errors are in JavaScript

Errors are just JavaScript’s way of saying, "I’m stuck!" There are three main types you'll see:

  • Syntax Errors: You made a typo or missed a bracket (The code won't even start).

  • Reference Errors: You’re trying to use a variable that doesn't exist.

  • Runtime Errors: The code is technically fine, but something went wrong while it was running—like trying to read data from a API's that is currently down.

Using try and catch blocks

Normally, when JavaScript hits an error, it panics and stops everything. To prevent this "painc," we use try and catch.

  • try: Put the code here that might be "risky" (like fetching data from an API).

  • catch: If something goes worng inside the try block, JavaScript jumps in catch block instead of crashing. It catches the error so you can handle it.

JavaScript:

try {
  console.log(myVariable); // This variable doesn't exist!
} catch (error) {
  console.log("Don't worry, I caught the error: " + error.message);
}

The finally block

The finally block doesn't care what happened "code failed" or "code succeeded" it always runs. It’s perfect for "cleanup" tasks, like closing a loading spinner or disconnecting connection from a database, regardless of what happened in the try or catch block.

Throwing custom errors

Sometimes, a piece of code is correct for JS, but it doesn't fit your rules. For example, if a user enters a negative age. You can "throw" your own error to stop the process by yourself using the throw keyword, just like this:

JavaScript:

if (age < 0) {
  throw new Error("Age cannot be negative!");
}

Why error handling matters

Without error handling, one tiny mistake can turn your entire website into a blank screen. Error handling allows the failure to be taken in your own hands. It means even if something goes wrong, you can show a message to the user like "Oops, something went wrong, please try again" instead of letting the website show a blank screen. It makes your website professional and much easier to debug!


A good developer doesn't just write code that works; they write code that knows how to fail gracefully. Catch those errors and keep building!