JavaScript throw
Example
This example examines input.
If the value is wrong, an exception (err) is thrown:
<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>
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 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:
Syntax
Parameters
The exception to throw.
Can be a string, number, boolean, or an object
Browser Support
break is an ECMAScript3 (JavaScript 1999) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |