Errors – JavaScript Basics

  1. try statement allows to analyse block of code for errors.
  2. catch statement allows to handle error.
  3. throw statement allows to create custom errors.
  4. finally statement allows to carry out code, after try & catch, regardless of result.

Try and Catch

JS statements try and catch come in pairs.

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}

Throws Error

throw "Too big";    // throw a text
throw 500;          // throw a number

You can simply generate custom error messages and control program flow if you use throw together with try and catch.

Input Validation

<!DOCTYPE html>
<html>
<body>
<p>Input Number Between 2 and 5 Below</p>

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

<script>
function myFunction() {
 var message, a;
 message = document.getElementById("message");
 message.innerHTML = "";
 a = document.getElementById("ex").value;
 try {
 if(a == "") throw "empty";
 if(isNaN(a)) throw "not a number";
 x = Number(a);
 if(a < 2) throw "Too Low!";
 if(a > 5) throw "Too High!";
 }
 catch(err) {
 message.innerHTML = "Input Is " + err;
 }
}
</script>

</body>
</html>

Output :

 

 

 

 

 

Finally Statement

<!DOCTYPE html>
<html>
<body>
<p>Input Number Between 2 and 5 Below</p>

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

<script>
function myFunction() {
 var message, a;
 message = document.getElementById("message");
 message.innerHTML = "";
 a = document.getElementById("ex").value;
 try {
 if(a == "") throw "is empty";
 if(isNaN(a)) throw "is not a number";
 a = Number(a);
 if(a > 5) throw "is Too High";
 if(a < 2) throw "is Too Low!";
 }
 catch(err) {
 message.innerHTML = "Input " + err;
 }
 finally {
 document.getElementById("ex").value = "";
 }
}
</script>

</body>
</html>

Output :

 

 

 

 

 

 

Leave a Reply

avatar
  Subscribe  
Notify of