JavaScript throw Statement Tutorial

In this section, we will learn what the throw statement is and how to use it in JavaScript.

Note: we’re assuming you’re already read the try catch section.

What is throw Statement in JavaScript? (Throwing Errors in JavaScript)

JavaScript automatically catches and throws errors when they appear in the program. But sometime we want to manually throw an error when part of our program doesn’t follow the logic that is defined for it.

In situations like this, we can use the `throw` keyword to create a statement that produces an error. This error, then, can be handled by a `catch` block.

throw Statement Syntax:

throw errorMessage;

On the right side of the `throw` keyword, we put a value (like a String value) that will be passed to the target `catch` block. We use this value in the `catch` block to see the reason for the error.

For example:

throw "Wrong password";

Here the value `”Wrong password”` will be passed to the target `catch` block and inside this block we can for example directly send this value to the browser’s console as the reason of the error so that the users (including developers) can see it. Or we can store this error in a file, etc.

Example: using throw statement in JavaScript

const rand = Math.random();
try{
  if (rand < 0.5){
    throw "The value should be higher than 0.5";
  }
}catch(error){
  console.log("Inside the catch block");
  console.log(error);
}
console.log("End");

Output:

Inside the catch block

The value should be higher than 0.5

End

As you can see, the message that we set on the right side of the `throw` keyword is passed to the `catch` block and for this particular example, we just sent the value to the console.

Note: The `random()` method will generate a value that is in a range from 0 to 1. Please check the `Math.random()` section to learn more about this method.

JavaScript Error Constructor Function

Usually, when using the `throw` keyword, we create an object via the `Error` constructor function or other constructor functions that are linked (prototype wise) to this `Error` function and pass the object to the target `catch` block.

This constructor function takes one argument and that is the message (reason) of the error.

Example: using JavaScript Error Constructor function

const rand = Math.random();
try{
  if (rand < 0.5){
    throw new Error("The value should be higher than 0.5");
  }
}catch(error){
  console.log("Inside the catch block");
  console.log(error.name);
  console.log(error.message);
}
console.log("End");

Output:

Inside the catch block

Error

The value should be higher than 0.5

End

The other constructor functions that the JavaScript engine will automatically use to generate an error are:

Name Description
Error The `Error` type is the base type from which all other error types inherit. As a result of this, all error types share the same properties.

An error of type `Error` is rarely, if ever, thrown by a browser; it is provided mainly for developers to throw custom errors.

InternalError The `InternalError` type is thrown when the underlying JavaScript engine throws an exception for example, when a stack overflow occurs from too much recursion. This is not an error type that we would explicitly handle inside our code; if this error is thrown, chances are very good that our code is doing something incorrect or dangerous and should be fixed.
RangeError A `RangeError` occurs when a number is outside the bounds of its range. For example, this error may occur when an attempt is made to define an array with an unsupported number of items, such as a negative value like -30.

Example:

let item1 = new Array(-30); //throws RangeError

ReferenceError The `ReferenceError` type is used when an object is expected. This type of error typically occurs when attempting to access a variable that doesn’t exist.

Example:

let obj = x; //throws ReferenceError when x isn’t declared

SyntaxError The `SyntaxError` object is thrown most often when there’s a syntax error in a JavaScript string that is passed to `eval()`.

Example:

eval(“a—b”)//throws SyntaxError

TypeError The `TypeError` type is the most used in JavaScript and occurs when a variable is of an unexpected type or an attempt is made to access a nonexistent method. This can occur for any number of reasons, most often when a type-specific operation is used with a variable of the wrong type.

Example:

let o = new 10; // throws TypeError

console.log(“Name” in true); //throws TypeError

Note: besides the engine, developers can use these constructor functions in their program if they need to.

JavaScript Rethrow an Exception

Rethrowing an exception basically means calling the `throw` operator in the body of a catch block that is handling an occurred error.

We rethrow an error because sometimes the catch handler that is currently handling an error might not do sufficient work and we have another enclosing handler that can run the rest of necessary tasks. So if we rethrow the error in the same form or another, then this error will reach to the enclosing handler and that can handle the rest of work.

Example: rethrowing an exception in JavaScript

function throwError(){
  try{
    console.log("Throwing an error");
    throw "This is a simple error";
  }catch(error){
    console.log("First handler catched the error but now rethrowing it!");
    throw error; 
  }
}

try{
  throwError();
}catch(error){
  console.log("The second handler catched the error");
  console.log(`Here's the message of the error: ${error}`);
}

Output:

Throwing an error
First handler catched the error but now rethrowing it!
The second handler catched the error
Here's the message of the error: This is a simple error

Reference book:

Professional JavaScript for Web Developers, 4th Edition.

Author: Matt Frisbie

More to Read:

JavaScript finally block tutorial 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies