Use of Try..catch statement in JavaScript

In this article I have described about error handling in JavaScript with Try..catch statement.
  • 2404

Try...catch Statement in JavaScript

For programming  point of view it is necessary for developer to handle the error or exception that occur at run time due to an illegal operation during execution.

The example of exceptions or errors are

  • Trying to reference an undefined variable.
  • Calling a non existent method.
  • Syntax error etc.

Try\Catch helps statement us to deal with exceptions gracefully. However it doesn't deal with Syntax error.

Syntax

try 


       //  JavaScript code that might cause an error 

catch (error) 

      //  JavaScript code for error message 
}

Example

<html xmlns="http://www.w3.org/1999/xhtml">

<html><title>Try\Catch Statement</title>

<head>

<script type="text/javascript">

var txt="";

function errormessage()

{

     try

     {

            adddlert("Welcome to MCN !");

     }

    catch(err)

     {

            txt="Sorry there is an error related to addalert. \n\n";

            txt+="Error type: " + err.errormessage + "\n\n";

            txt+="Do you want to continue ! Press OK .\n\n";

            alert(txt);

     }

}

</script>

</head>

     <body>

          <input type="button" value="error message" onclick="errormessage()" />

    </body>

</html>

Output

try1.jpg

when we click on "errormessage" button, then

try2.jpg

Further Readings

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.