JavaScript Throwing Exceptions

Sometimes when a program runs, unexpected problems happen. These problems are called exceptions. In JavaScript, you can use the throw statement to tell your program when something goes wrong. This page will explain how to throw exceptions, how to create your own types of errors, and how to handle these errors safely.



What is an Exception?

An exception happens when something unexpected or wrong occurs while your program is running. For example, trying to use a negative number when only positive numbers make sense, or trying to use a username that is empty.

When an exception happens, JavaScript stops running the current code and looks for a way to handle the problem. If it can’t find any handling code, the program will stop and show an error message.

How to throw an Exception

You can use the throw statement to create an exception yourself. This means you are telling JavaScript: “Something went wrong here!” You usually throw an Error object with a message explaining what the problem is.

javascript
throw new Error("This is an error message");

The above code will stop the program and show the message "This is an error message".

Example: Throwing a Built-in Error

Let’s say you have a function that sets a person’s age. You want to make sure the age is not negative, because negative ages don’t make sense. You can throw an exception if a bad age is given:

javascript
function setAge(age) {
  if (age < 0) {
    throw new RangeError("Age cannot be negative");
  }
  console.log("Age set to", age);
}

setAge(-3); // This will throw an error

In this example, we throw a RangeError, which is a special kind of error JavaScript already knows about.

What Happens if You Don't Handle Errors?

If your program throws an exception and there is no code to catch it, your program will stop running and show an error message like this:

bash
Uncaught RangeError: Age cannot be negative

Creating Custom Error Types

Sometimes you want to make your own types of errors, especially if your program has specific rules or checks. For example, you might want an AuthenticationError if a user login fails, or a ValidationError if the input is wrong.

How to Create a Custom Error

To create your own error type, you can make a new class that extends the built-in Error class. This means your custom error will behave like a normal error but with your own name and message.

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

function validateUsername(username) {
  if (!username) {
    throw new ValidationError("Username is required.");
  }
  console.log("Username is valid:", username);
}

validateUsername(""); // Throws ValidationError

Here, we create a ValidationError and throw it if the username is missing.

Catching Custom Errors

You can catch custom errors just like built-in errors. Use instanceof to check if the error is your custom type and handle it specially:

javascript
try {
  validateUsername("");
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Validation failed:", error.message);
  } else {
    throw error; // Re-throw unknown errors
  }
}

Why Create Custom Errors?

  • Make your code easier to understand.
  • Handle different errors in different ways.
  • Provide clear and specific error messages.

Creating custom errors helps you write programs that are easier to debug and maintain.


Example 1: Throwing an Error When Input Is Missing

You can use throw inside a function to stop the code when something is wrong. In this example, we’ll throw an error if a required input is missing:

javascript
function sayHello(name) {
  if (!name) {
    throw new Error("Name is required");
  }
  console.log("Hello, " + name + "!");
}

sayHello("Jane");   // Works fine
sayHello("");         // Throws an error

How It Works:

  • if (!name): Checks if the name is missing or an empty string.
  • throw new Error("Name is required"): Stops the function and shows an error message.
  • If a name is given, it prints a greeting message with console.log.

Output

Hello, Jane!
Uncaught Error: Name is required

Example 2: Throwing an Error for a Short Password

Let’s say you want users to create a password that is at least 6 characters long. You can throw an error if the password is too short:

javascript
function setPassword(password) {
  if (password.length < 6) {
    throw new Error("Password must be at least 6 characters long");
  }
  console.log("Password accepted");
}

setPassword("123456");  // Works fine
setPassword("abc");     // Throws an error

How It Works:

  • password.length < 6: Checks if the password is too short.
  • throw new Error(...): Stops the function and shows a clear message.
  • If the password is long enough, it prints "Password accepted".

Output

Password accepted
Uncaught Error: Password must be at least 6 characters long

Example 3: Throwing an Error If a Number Is Not Even

This example checks if a number is even. If it’s not, we throw an error. This shows how you can enforce simple rules in your code using throw.

javascript
function checkEven(number) {
  if (number % 2 !== 0) {
    throw new Error("Only even numbers are allowed");
  }
  console.log(number, "is even");
}

checkEven(4); // Works fine
checkEven(5); // Throws an error

How It Works:

  • number % 2 !== 0: Checks if the number is odd.
  • If the number is not even, we throw an error with a message.
  • If it is even, we log that it passed the check.

Output

4 is even
Uncaught Error: Only even numbers are allowed

Frequently Asked Questions

What does the throw statement do in JavaScript?

The throw statement allows you to manually trigger an error. This stops the current function and sends the error to be handled by a surrounding try-catch block, if available.


What types of values can I throw in JavaScript?

You can throw any value in JavaScript, including strings and objects. However, it's best practice to throw an instance of Error or a custom error class for consistency and better debugging.


What happens after I use throw in my code?

When a throw statement is executed, JavaScript stops the current operation and looks for a try-catch block to handle the exception. If none exists, the program may terminate unexpectedly.


Why should I throw custom errors?

Custom errors make your code easier to understand and debug. You can provide specific names and messages that explain what went wrong, and handle different types of errors in different ways.


Is throw only for built-in errors?

Not at all. You can define your own custom error classes by extending the built-in Error class and use throw to raise them. This is useful for handling specific logic like form validation or permission checks.



What's Next?

In the next section, we’ll learn about classes, objects, and constructors in JavaScript. These are important building blocks that help you organize your code and create reusable pieces. Don’t worry if you’re new to these ideas—we’ll break everything down in a simple and easy-to-follow way!