JS Exceptions

By using JS we can handle exceptional conditions. Similar to Java, there are try, catch, throw and finally statements in JS.

The try…catch statement allows us to test a block of code for errors. The “try” block contains the code to be run, and the “catch” block contains the code to be executed if an error occurs.

The throw statement can be used together with the try…catch statement, to create a custom error.

The finally statement allows us to execute code, after the try…catch statement, regardless of the result.

See the coding examples below.

Example 1

<html>
<body>
<h3>JS Exception</h3>

<script>
try {
document.write("inside try!" + "<br>");
eval("alert('text)"); // missing ' in 'text' will generate an error
}
catch(err) {
document.write("<br>" + "inside catch!" + "<br>");
document.write("Exception: " + err + "<br>");
}
finally {
document.write("<br>" + "inside finally!" + "<br>");
}
</script>

</body>
</html>

Output:

JS Exception

inside try!

inside catch!
Exception: SyntaxError: Invalid or unexpected token

inside finally!

 

Example 2

<html>
<body>

<p>Input a two digit number:</p>

<input id="test" type="text">
<button type="button" onclick="testMethod()">Test Input</button>

<p id="demo"></p>

<script>
function testMethod() {
var msg, v;
msg = document.getElementById("demo");
msg.innerHTML = "";
v = document.getElementById("test").value;

try {
if(v == "")
throw "Empty!";
if(isNaN(v))
throw "Not a number!";

v = Number(v); //convert into number

if(v > 99)
throw "Three digit!";
else if(v < 10)
throw "One digit!";
else
msg.innerHTML = "Input " + v + " is correct.";
}
catch(err) {
msg.innerHTML = "Input is: " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>

</body>
</html>

Output: