Throw and Custom Error - JavaScript

 

Errors in JavaScript are like plot twists in movies—you never see them coming, but they happen! Luckily, JavaScript gives us throw and custom errors so we can control the chaos instead of just screaming at the screen. Let's dive in and see how we can create, throw, and handle errors like a pro! 

1. What is throw

In JavaScript, the throw statement is used to throw (a.k.a. launch) an error intentionally. This helps you control when and how an error should happen.

Example:

throw new Error("Something went wrong!");

Boom! Instant panic. But don't worry, we can handle this elegantly with try...catch (which we’ll see later).

2. Throwing Different Types of Errors

JavaScript has built-in error types, and we can throw them manually!

Example:

throw new TypeError("This is not the right type!");
throw new ReferenceError("Oops! This variable doesn’t exist.");
throw new SyntaxError("Check your syntax, buddy!");

This is like JavaScript’s way of saying, "Hey, fix this before I crash everything!"

3. Creating Custom Errors

Sometimes, the default errors don’t quite express our frustration correctly. That's where custom errors come in!

Example:

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}

throw new CustomError("This is a totally custom error!");

Now you can define errors that make sense in your application. Pretty cool, right?

4. Handling Errors Gracefully 

Throwing errors is great, but handling them is even better! Enter try...catch.

Example:

try {
  throw new CustomError("Something went terribly wrong!");
} catch (error) {
  console.error(`Caught an error: ${error.name} - ${error.message}`);
} finally {
  console.log("Error or no error, I always run! 🎭");
}

The finally block is like the reliable friend who stays with you no matter what happens. 

Conclusion 

Errors in JavaScript don’t have to be scary! By using throw, custom errors, and try...catch, you can handle mistakes like a coding ninja.


Post a Comment

0 Comments