Tuesday, 12 October 2010

How to Handle Error in JavaScript | Try Catch Block

JavaScript Coding Steps for Error Handling:

1. Use try block outside the code and handle errors in catch block as given below.

2. You can log the error for debugging purpose.

Try Catch Blocks in JavaScript:

<html>
<head>
<script type="text/javascript">
var My_Error="";
try
  {
  adddlert("This is JavaScript Try Catch Demo!");
  }
catch(ex)
  {
  My_Error="You have reached to catch block.\n\n";
  My_Error+="Error description: " + ex.description + "\n\n";
  alert(My_Error);
  }
</script>
</head>
</html>

Try Catch block Output:

How to Handle Error in JavaScript | Try Catch Block

How to Run this program:

1. Copy the code above and paste to notepad file

2. Save file as SomeFileName.html (Please note that give file extension to .html or .htm)

3. Open this file in Internet explorer.

No comments:

Post a Comment