Google News
logo
Javascript Error Handling
The latest versions of JavaScript added exception handling capabilities. 

JavaScript errors are :

1. The try statement allows you to define a block of code to be tested for errors while it is being executed.
2. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
3. The throw statement allows you create custom errors.
4. The finally statement lets you execute code, after try and catch, regardless of the result.
JavaScript try and catch :
The JavaScript try and catch statements syntax :
try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}
Example :
<html>
<head>
<title>Javascript try ....catch statement.</title>
</head>
<body>
 
<p id="error_Mesg"></p>

<script type="text/javascript">
try
{
var result  =  Sum(15, 21); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("error_Mesg").innerHTML = ex;
}
    </script>
 
</body>
</html>
Output :

ReferenceError: Sum is not defined

JavaScript throw Statement :
<html>
<head>
<title>Javascript throw statement.</title>
</head>
<body>
 
<h3 id="error_Mesg"></h3>
 
<script type="text/javascript">
    try
    {
        throw {
            number : 404,
            message : "This webpage is not available !"
        };
    }
    catch(ex)
    {
        document.getElementById("error_Mesg").innerHTML = ex.number + " - " + ex.message;
    }
</script>
 
</body>
</html>
Output :

404 - This webpage is not available !

Javascript finally Statement :
<html>
<head>
<title>Javascript finally statement.</title>
</head>
<body>
 
<p id="error_Mesg">Error : </p>
<p id="mesg"></p>
 
<script type="text/javascript">
    try
    {
         var result  =  Sum(15, 21); // Sum is not defined yet
    }
    catch(ex)
    {
        document.getElementById("error_Mesg").innerHTML += ex;
    }
    finally{
        document.getElementById("mesg").innerHTML = "finally block executed";
    }
 
</script>
 
</body>
</html>
Output :

Error : ReferenceError: Sum is not defined

finally block executed