Error Handling Basics

Back

Loading concept...

Error Handling Basics: Your Code’s Safety Net 🛡️

The Story of the Tightrope Walker

Imagine you’re watching a circus performer walking on a tightrope high above the ground. What’s directly below them? A safety net!

The performer hopes to walk across perfectly, but accidents happen. Without that net, one slip means disaster. With the net? They fall safely, get back up, and try again.

That’s exactly what error handling does for your code.

Your JavaScript program is the tightrope walker. Errors are the slips. And try-catch is your safety net.


Why Do We Need Error Handling?

Think about what happens when you:

  • Divide a number by zero
  • Try to read a file that doesn’t exist
  • Ask a website for data, but the internet is down

Without error handling, your program crashes. The whole show stops. Users see ugly error messages. Everyone is unhappy.

With error handling, your program catches the problem, handles it gracefully, and keeps running.


1. The try-catch Statement

What Is It?

try-catch is like saying:

“Hey JavaScript, TRY to do this thing. If something goes wrong, CATCH the problem so we can deal with it.”

The Syntax

try {
  // Code that might cause an error
  // This is the "risky" stuff
} catch (error) {
  // What to do if something goes wrong
  // This is your safety net
}

A Simple Example

try {
  let result = 10 / 0;
  console.log("Result:", result);
} catch (error) {
  console.log("Oops! Something broke!");
}

Real-World Example

Imagine you’re trying to parse some JSON data from a user:

try {
  let userData = '{"name": "Sam"';
  let user = JSON.parse(userData);
  console.log("Hello,", user.name);
} catch (error) {
  console.log("Bad data! Can't read it.");
}

The JSON is broken (missing }), so JSON.parse fails. But instead of crashing, we catch the error and show a friendly message.


2. The throw Statement

What Is It?

Sometimes YOU are the one who notices something is wrong. You’re not waiting for JavaScript to fail—you’re saying:

“Wait! This isn’t right! I’m THROWING this error myself!”

It’s like a referee blowing a whistle when they see a foul.

The Syntax

throw new Error("Your message here");

A Simple Example

function checkAge(age) {
  if (age < 0) {
    throw new Error("Age can't be negative!");
  }
  return "Age is valid: " + age;
}

Using throw with try-catch

try {
  let age = -5;
  if (age < 0) {
    throw new Error("Negative age? Impossible!");
  }
  console.log("Your age:", age);
} catch (error) {
  console.log("Problem:", error.message);
}
// Output: Problem: Negative age? Impossible!

When to Use throw

  • User enters invalid data
  • A required value is missing
  • Something that “should never happen” happens

3. The finally Block

What Is It?

finally is code that ALWAYS runs—whether there was an error or not.

Think of it like this: After the tightrope performance, whether they made it across OR fell into the net, the cleanup crew still comes out to pack up the equipment.

The Syntax

try {
  // Risky code
} catch (error) {
  // Handle the error
} finally {
  // This ALWAYS runs
  // Cleanup goes here
}

A Simple Example

try {
  console.log("Starting...");
  throw new Error("Oops!");
} catch (error) {
  console.log("Caught:", error.message);
} finally {
  console.log("Cleaning up!");
}
// Output:
// Starting...
// Caught: Oops!
// Cleaning up!

Even Without Errors, finally Runs

try {
  console.log("Everything is fine!");
} catch (error) {
  console.log("Error:", error.message);
} finally {
  console.log("Finally runs anyway!");
}
// Output:
// Everything is fine!
// Finally runs anyway!

When to Use finally

  • Closing a file you opened
  • Stopping a loading spinner
  • Cleaning up temporary data
  • Releasing resources

4. The Error Object

What Is It?

When an error happens, JavaScript creates an Error object. This object holds information about what went wrong.

It’s like a police report: “Here’s what happened, where it happened, and why.”

Key Properties

Property What It Tells You
message A description of the error
name The type of error
stack Where the error happened

Accessing Error Properties

try {
  throw new Error("Something broke!");
} catch (error) {
  console.log("Name:", error.name);
  console.log("Message:", error.message);
}
// Output:
// Name: Error
// Message: Something broke!

Types of Built-in Errors

JavaScript has several error types:

// SyntaxError - Code is written wrong
// ReferenceError - Using undefined variable
// TypeError - Wrong type used
// RangeError - Number out of range

Example: ReferenceError

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

Creating Custom Errors

try {
  let password = "123";
  if (password.length < 8) {
    throw new Error("Password too short!");
  }
} catch (error) {
  console.log(error.message);
}
// Output: Password too short!

Putting It All Together

Here’s a complete example using everything:

function divide(a, b) {
  try {
    if (b === 0) {
      throw new Error("Cannot divide by zero!");
    }
    let result = a / b;
    console.log("Result:", result);
    return result;
  } catch (error) {
    console.log("Error:", error.message);
    return null;
  } finally {
    console.log("Division attempt complete.");
  }
}

divide(10, 2);
// Result: 5
// Division attempt complete.

divide(10, 0);
// Error: Cannot divide by zero!
// Division attempt complete.

The Flow: A Visual Summary

graph TD A["Start try block"] --> B{Error occurs?} B -->|Yes| C["Jump to catch block"] B -->|No| D["Continue normally"] C --> E["finally block runs"] D --> E E --> F["Program continues"]

Quick Reference

Keyword Purpose When It Runs
try Wrap risky code Always attempted
catch Handle errors Only if error occurs
throw Create an error When you call it
finally Cleanup code Always, no matter what

Remember the Circus! 🎪

  • try = The tightrope walk
  • catch = The safety net
  • throw = The performer signals “I’m falling!”
  • finally = The cleanup crew
  • Error object = The incident report

With these tools, your code can handle the unexpected gracefully. No more crashes. No more panicked users. Just smooth, professional error handling.

Your code now has a safety net. Use it!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.