English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript throw statement

 JavaScript Statements and Variable Declarations

throwstatement throws a user-defined exception.

When an error occurs, JavaScript usually stops and generates an error message. Technically, this is called a " throw error "

The throw statement allows you to create custom errors. Technically, this is called a " Throw an exception "

when an exception is thrownexpression (expression)Specify the value of the exception. The following will all cause an exception:

throw 'Invalid';  // generate an exception with a string value
throw 32; // generate a value of32exception
throw true;   //generate an exception with a value of true

If you use throw andtry and catchWhen used together, they can control the flow of the program and generate custom error messages.

You can find more information in ourIn the JavaScript exception tutorialLearn more about exceptions.

Syntax:

throw expression;

function getRectArea(width, height) {
   if (isNaN(width) || isNaN(height)) {
  throw "Parameter is not a number!";
   }
}
try {
   getRectArea(5, 'Z');
}
catch(err) {
   ;document.getElementById('para').innerHTML = err;
}

Test and See‹/›

Browser compatibility

All browsers fully support the throw statement:

Statement
throwIsIsIsIsIs

Parameter value

ParameterDescription
expressionThrow an exception. It can be a string, number, boolean, or object

Technical details

JavaScript version:ECMAScript 3

More Examples

In this example, if the value is incorrect, an exception (err) is thrown. The catch statement catches the exception (err) and displays a custom error message:

var x = document.querySelector("input").value;
try {
   if(x == "") throw "Is Empty";
   if(isNaN(x)) throw "Is not a number";
   if(x > 10) throw "Too large";
   if(x < 5)throw "Too small";
}
catch(err) {
   document.getElementById("para").innerHTML = "Input" + err;
}
Test and See‹/›

Related References

JavaScript Tutorial:JavaScript Exceptions

JavaScript Reference:JavaScript try ... catch Statement

 JavaScript Statements and Variable Declarations