The try...catch statement allows you 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.

Syntax

try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!


Example

<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.description + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>


<body>
<input type="button" value="View message" onclick="message()" />
</body>


</html>


This entry was posted on 4:23 AM and is filed under , , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

0 comments: