The try...catch is a common error handling block in all programming languages. It is mostly used to handle error that are likely to occur during code execution.
It is always a good practice to place all codes that may possibly or likely trigger error in the try...catch block so that the program flow will not be disrupted if at all any error occurs.
Having a thorough understanding of each block of the try...catch statement will make you to understand why and when to use it.
try
{
code to execute;
}
catch(error)
{
code to execute;
}
The try{} block or segment is where the code that needs to be checked for any possible error is placed.
If any error occurred, then the try{} execution is paused and while the catch{} block execution start immediately by taking suitable actions and handling the error.
Unlike the try{} block where code is test for error checking, the catch{} block wait for the try{} block execution to see if any error will occur else catch{} block execution remains dormant and skipped.
In other words, it executes only when any error code needs to be handled in the try block.
This block contains either the user-defined exception handler or the built-in handler.
To learn more about Exception handler, check
what is exception handling in Javascript
Until the try{} block is executed and error detected, the catch{} is never executed. Also, one try block can contain one or more catch blocks.
In the following example, we are going to sum two values and display the output and also try to display another value that is declared.
<html>
<head>
<title>Try... catch example</title>
<script>
function sum(){
var a = 4;
var b = 6;
var c;
try{
c = parseInt (a) + parseInt (b);
alert (c); // c is declared
alert (d);// d is not declared
}
catch (e){
alert ("The following error occurred: " + e.message);
}}
sum();
</script>
</head>
<body>
</body>
</html>
The throw statement can be used to throw custom errors. When throw statement is executed, the statements present after it will not execute. The control will directly pass to the catch block.
try…catch…throw syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; // code for handling exception}
In the example below, the program will prompt the user to input any number between 1 and 3
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 1and 3</p>
<input id="txtnum" type="text">
<button type="button" onclick="test()">Test Input</button>
<script>
function test() {
var myinput = document.getElementById("txtnum").value;
try {
if(myinput == "") throw "is empty";
if(isNaN(myinput)) throw "not a number";
if(myinput > 3) throw "greater than maximum input";
if(myinput < 1) throw "lower than minimum input";
}
catch(err) {
alert ("Input " + err);
}
}
</script>
</body>
</html>
Run the program to see output.
With the help of throw statement, users can create their own errors.
Finally is an optional block of statements which is executed after the execution of try and catch statements. Whether exception is thrown or not, finally block code, if present, will definitely execute.
try{
expression; }
catch(error){
expression; }
finally{
expression; //Executable code }
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var x=10;
var y = 2;
var y = parseInt (x) + parseInt (y);
if(y == 12)
alert("The sum is 12");
}
catch(e){
document.write("Error occurred"+ e.message);
}
finally{
alert("I "finally" will execute no matter what!");
}
</script>
</body>
</html>
Note, you can also use try...catch...throw...finally keyword together for handling complex code.