If the value is wrong, an exception (err) is thrown. - Javascript Statement

Javascript examples for Statement:try catch finally

Introduction

The exception (err) is caught by the catch statement and a custom error message is displayed:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

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

<script>
function myFunction() {/*from   ww w .  jav a  2  s.c  om*/
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    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>

</body>
</html>

Related Tutorials