Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Updated
3 min readView as Markdown
Error Handling in JavaScript: Try, Catch, Finally

In a perfect world, code runs smoothly. In the real world, servers go down users type "banana" into age fields, and API returns unexpected nulls. Without a safety net these hiccups don't just cause glitches—they crash your entire application.

Here's you can use try, catch, and finally to keep your JavaScript running even when things go wrong.

What are Errors in JavaScript?

In JavaScript, an error is an object that represents an abnormal condition. When the engine encounters something it can't handle—like calling a function that doesn't exist—it "throws" an error.

Common Runtime Errors include:

  • ReferenceError: Using a variable that hasn't been declared.

  • TypeError: Performing an operation on the wrong data type (e.g., null.map()).

  • SyntaxError: Writing code that the engine literally cannot read (though these usually stop the script before it even starts).

The Safety Net: try and catch

The try...catch statement allows you to test a block of code for errors while defining a specific way to handle them if they occur. This is known as graceful failure.

try {
  // Code that might fail
  const data = JSON.parse(invalidJsonString); 
  console.log("This line will not run if an error occurs above.");
} catch (error) {
  // Code to handle the error
  console.error("Oops! We couldn't parse that data:", error.message);
}
  • The try block: You wrap the risky code here.

  • The catch block: If an error occurs in the try block, execution jumps here immediately. The error object provides details like the name and message.

The "Clean Up" Crew: The finally Block

Sometimes, you need code to run regardless of whether an error happened or not. This is where finally comes in. It’s most commonly used for "cleanup" tasks, like closing a database connection or hiding a loading spinner.

let isLoading = true;

try {
  fetchData();
} catch (err) {
  showErrorMessage();
} finally {
  isLoading = false; // This runs no matter what
  console.log("Request attempt finished.");
}

Taking Control: Throwing Custom Errors

You don’t have to wait for JavaScript to notice a problem. You can throw your own errors based on business logic using the throw keyword.

function withdrawMoney(amount, balance) {
  if (amount > balance) {
    throw new Error("Insufficient funds!"); // Creating a custom error
  }
  return balance - amount;
}

try {
  withdrawMoney(100, 50);
} catch (e) {
  console.log(e.message); // "Insufficient funds!"
}

Why Error Handling Matters

Writing error-handling code might feel like extra work, but it’s the hallmark of a professional developer for three reasons:

  1. Graceful Failure: Instead of a white screen or a frozen "Submit" button, the user gets a helpful message: "Sorry, we're having trouble reaching the server. Please try again later."

  2. Debugging Benefits: By catching errors and logging them (to the console or a service like Sentry), you get a clear map of exactly where and why your app failed.

  3. Security: Unhandled errors can sometimes leak sensitive stack trace information to the browser. Proper catch blocks allow you to control exactly what the user sees.

Summary Table

Block Purpose Required?
try Contains the code that might cause an error. Yes
catch Executes only if an error is thrown in the try block. Optional (if finally is present)
finally Executes after try and catch, regardless of the outcome. Optional
1 views