Thursday, January 13, 2011

JavaScript Error Handling

JavaScript allows developers to deal with error handling with the help of following two constructs:

  1. try/catch block
  2. onError event

Basically developers need to use error handling concept in code structure simply because end users of your application may get confused or may be irritated to see alert boxes with errors and in such case user often leave the Web page. And so error handling plays a vital role in such scenarios.
Now we will learn about constructs of error handling in JavaScript mentioned above.

try/catch block:
--
Syntax:

try {
//Executable script
}
catch (errorObject) {
//Error handler
}
finally {
//Code to execute all the time,irrespective of error occurrence.
}
--
The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Whenever an error occurs while processing code present in try block, it will hand it over to catch block for executing the code present in it.

onError event:
--
Syntax:

window.onerror=function(){
//code to run when error has occured on page
}
--
'onerror' event is fired at the moment JavaScript error occurs in a script. So as a habit of good conduct it is always advisable to place code 'onerror' event at the top of the page so that all JavaScript errors can be successfully intercepted.

4 comments:

  1. like it,

    Its very useful while error tracking in JS.

    ReplyDelete
  2. Have you tested against cross browser?

    ReplyDelete
  3. @Pawan: Yes this JS block has no browser compatibility issues as far as I have tested. Kindly revert back if you come across any such issues.
    Thanks!

    ReplyDelete
  4. I have used the "try/catch block" in case of IE7.
    IE8 and FF both works in same manner for DOM redering and javascripts. :) Thanks.

    ReplyDelete