Account
Categories

Throw Error


Definition:

It is a part of error handling that sends an error to the catch block, and the main difference is that it uses a custom error created by the programmer based on their requirements.

You can use it with try-catch error handling method.

When the program runs, JavaScript executes the code line by line until it reaches the throw statement.

When the program reaches a throw statement, it immediately stops execution and shows the custom error.
So, a throw error is a custom error that you can create yourself whenever you want.

Now you can clearly understand how throw error works with the help of this flowchart.

Start
  |
  v
Write your code in a Try block
  |
  v
Run Try block
  |
  v
Is there any error?
   /      \
 Yes        No
  |          |
  v          v
Run Catch   Try block
  block      finishes
  |           |
  v           v
Show "error"  End
  |
  v
 End

Syntax:

throw "Error message";

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Throw Error Example</title>
</head>
<body>
  <h1>JavaScript Throw Error Example</h1>
  <p>Open the console (F12) to see the output.</p>

  <script>
    // Throw Error Example
    try {
        let age = 15;  // This is wrong age

        if (age < 18) {
            throw new Error("Age must be 18 or above!"); 
        }

        console.log("Access Granted!");
    }
    catch (error) {
        console.log("Error: " + error.message);
    }
  </script>
</body>
</html>

Output:

Error: You must be 18 or above!