JavaScript throw

Example

This example examines input.

If the value is wrong, an exception (err) is thrown:

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {
  const message = document.getElementById("message");
  message.innerHTML = "";
  let x = document.getElementById("demo").value;
  try {
    if(x == "") throw "is Empty";
    if(isNaN(x)) throw "not a number";
    if(x > 10) throw "too high";
    if(x < 5) throw "too low";
  }
  catch(err) {
    message.innerHTML = "Input " + err;
  }
}
</script>
Try it Yourself »

Description

The throw statement allows you to create a custom error.

The throw statement throws (generates) an error.

The technical term for this is:

The throw statement throws an exception.

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big";  // throw a text
throw 500;        // throw a number
throw false;      // throw a boolean
throw person;     // throw an object

Note

Using throw with try and catch, lets you control program flow and generate custom error messages.

See Also:

The JavaScript try...catch...finally

JavaScript Error Object

JavaScript Errors Tutorial



Syntax

throw expression;

Parameters

Parameter Description
expression Required.
The exception to throw.
Can be a string, number, boolean, or an object

Browser Support

break is an ECMAScript3 (ES3) feature.

ES3 (JavaScript 1999) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.