- Tags: Error, JS Statement
- Categories: JavaScript Reference, JavaScript Statements, Reference
Quick Reference
The throw statement allows you to generate a custom error (throw an exception), which can be a String, a Number, a Boolean, or an Object.
In the following, we use x as our value (let’s say it was input by the user in a form field). The user was asked to input a number between 1 and 5.
We then use the throw statement to look for errors (try) and output them (catch) to the html element.
If no errors are found, nothing will be output using the “catch”, and the code will continue to run after line 13.
// variable
let x = 13;
// throw statement
try {
if(x == '') throw 'You did not enter a value.';
if(isNaN(x)) throw 'You did not enter a number.';
if(x > 5) throw 'The number entered is too high.';
if(x < 1) throw 'The number entered is too low.';
}
catch(err) {
document.getElementById('my_output').innerHTML = err;
}
Output
The number entered is too high.
Syntax
condition throw 'message';
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.
Why 1SMARTchicken?
See More →
Thanks for your support!
JavaScript Books
All are affiliate links. Thank you for your support!
JAVASCRIPT NOTES:
- When using JavaScript, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
- JavaScript is a case-sensitive language; firstName is NOT the same as firstname
- Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on
- JavaScript variables must begin with a letter, $, or _
- JavaScript variables are case sensitive (x is not the same as X)
Feedback
If you see an error on the page or the code itself is incorrect or incomplete, or just plain wrong, please let us know. We’re always learning. NOTE: we do not sell your information and will not send you spam emails.