Did you find this useful?
Socialize it today.


JavaScript Throw

Monday, April 16, 2012

The JavaScript throw statement allows you to create an exception. The throw statement is used in conjunction with the try and catch statements we learned about in the previous tutorial. The throw statement allows you to control the program flow. Here is an example of the throw syntax.


throw exception


The exception can be defined as an integer, string, Boolean, or an object. Here is an example of how to use the throw statement in conjuction with the try and catch JavaScript statements.


<html>
<body>
<script type="text/javascript">
    var x = prompt("Input a number between 10 and 20:", "");
    try 
    {
        if (x < 10) {
            throw "errorLow";
        }
        else if (x > 20) {
            throw "errorHigh";
        }
        else {
            alert("Good job following directions!");
        }
    }
    catch (err) 
    {
        if (err == "errorLow") {
            alert("Your number is less than 10.");
        }
        if (err == "errorHigh") {
            alert("Your number is greater than 20.");
        }
    }
</script>
</body>
</html>

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Professional JavaScript for Web Developers HTML CSS and JavaScript Editor JavaScript and jQuery: The Missing Manual