Error Handling in JavaScript: Try, Catch, Finally

Published: (April 4, 2026 at 01:45 AM EDT)
3 min read
Source: Dev.to

Source: Dev.to

🚨 What Are Errors in JavaScript?

Errors are problems that occur during code execution (runtime).

Example

console.log(x); // ❌ ReferenceError: x is not defined

Common Types of Errors

  • ReferenceError – variable not defined
  • TypeError – wrong type usage
  • SyntaxError – invalid code

😵 The Problem Without Error Handling

function divide(a, b) {
  return a / b;
}

console.log(divide(10, 0));
console.log("This may still run...");

Some errors can break your app or cause unexpected behavior.

💡 Using try and catch

The try...catch block lets you handle errors safely.

try {
  let result = riskyFunction();
  console.log(result);
} catch (error) {
  console.log("Something went wrong:", error.message);
}

📊 Flow

try block runs

error occurs?
   ↓ yes
catch block runs

program continues safely

📥 Understanding the catch Block

try {
  console.log(x);
} catch (error) {
  console.log(error.name);    // ReferenceError
  console.log(error.message); // x is not defined
}

The error object provides useful debugging information.

🧹 The finally Block

The finally block always runs—whether an error occurs or not.

try {
  console.log("Trying...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("This always runs");
}

📊 Execution Order

try → catch (if error) → finally

🔥 Throwing Custom Errors

You can create your own errors using throw.

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient balance");
  }
  return balance - amount;
}

try {
  withdraw(1000, 1500);
} catch (err) {
  console.log(err.message);
}

🧠 Why Use Custom Errors?

  • Better debugging
  • Clear error messages
  • Control program flow

🛠️ Real-World Example

function parseJSON(data) {
  try {
    return JSON.parse(data);
  } catch (err) {
    console.log("Invalid JSON");
    return null;
  }
}

❓ Why Error Handling Matters

  • ✅ 1. Prevents Crashes – Your app keeps running even when something fails.
  • ✅ 2. Better User Experience – Users see meaningful messages instead of broken screens.
  • ✅ 3. Easier Debugging – You get clear insights into what went wrong.
  • ✅ 4. Graceful Failure

Bad:

// app crashes ❌

Good:

// show error message ✅
// continue execution ✅

⚠️ Important Notes

  • try...catch only works for runtime errors.
  • It does not catch syntax errors.
  • Works synchronously (async needs special handling like async/await).

🧠 Best Practices

  • Keep try blocks small.
  • Use meaningful error messages.
  • Don’t ignore errors silently.
  • Use finally for cleanup (closing resources, etc.).

🚀 Final Thoughts

Error handling is not optional—it’s essential. Using try, catch, and finally, you can:

  • Build robust applications.
  • Handle failures gracefully.
  • Improve debugging and maintenance.

🧠 Quick Summary

  • Errors happen at runtime.
  • try → test code.
  • catch → handle errors.
  • finally → always runs.
  • throw → create custom errors.
0 views
Back to Blog

Related posts

Read more »

Spread vs Rest Operators in JavaScript

!Cover image for Spread vs Rest Operators in JavaScripthttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%...

Destructuring in JavaScript

Have you ever written code like this? js // repetitive extraction const numbers = 10, 20, 30; const first = numbers0; const second = numbers1; It works—but it’s...

Synchronous vs Asynchronous JavaScript

JavaScript is single‑threaded, yet it can handle multiple tasks efficiently by using synchronous and asynchronous behavior. What Is Synchronous Code? Synchronou...

Understanding Functions in JavaScript

What is a Function? A function is a block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can write it once insid...