Implementing exception handling in JavaScript
I would like to know the best and easiest way to implement exception handling in Javascript. I'm looking for a "one point" solution. I've got lot of functions and wouldn't want to go around and implement try-catch.
I feel window.onerror would be a better approach, since I just have to implement this in one place and any exceptions that occurs in any of the functions, I would be able to handle it using window.onerror. However, this seems to be supported only in IE. Is there any similar way that I can use so that it supports all major standard browsers.开发者_运维问答
Thanks in advance.
Using try..catch block
try..catch block in JavaScript is very much similar to the regular C# try..catch block. The suspected code will be put in try block and all exceptions which will occur in the try block will be caught in catch block.
window.onload = function()
{
try
{
var x = 90;
var value = x / y;
}
catch(err)
{
document.write(err.name + ": " + err.message + "<br/>");
}
}
Output:
TypeError: 'y' is undefined
In catch you will get the object containing type and description of the exception. More over you can also use finally block in the same way as you use in C#.
window.onload = function()
{
try
{
var x = 90;
var value = x / y;
}
catch(err)
{
document.write(err.name + ": " + err.message + "<br/>");
}
finally
{
alert('This is finally block');
}
}
Using onerror event
onerror event will be raised each time there is any error while performing a action in the document. This like on place exception handling similar to Application_Error in ASP.NET. Here is sample code which demonstrate this:
window.onload = function()
{
var x = 90;
var value = x / y;
}
window.onerror = function(errorMeaage, fileName, lineNumber)
{
document.write('Error: ' + errorMeaage);
}
Using jQuery Solution
It is similar to using onerror but with jQuery syntax. The syntax is:
$(window).error(
function(errorMeaage, fileName, lineNumber)
{
// handle error here
}
);
Excerpt from JavaScript Exception Handling Techniques
If there are just a handful of functions calling each other, I'd do something like this.
try{
main();
}
catch(e){
//error
}
Where main() would be the function that calls everything else; a la, the entry point within your script. Although, this doesn't leave you with a lot of flexibility in the code called below. So consider making different "levels" of functions, where each call to them is wrapped in a try...catch block where you can handle them appropriately. ie.
function a(){}
function b(){}
function main(){
//call a, catch any errors
try{
a();
}
catch(e){}
//call b, catch any errors
try{
b();
}
catch(e){}
//and so on...
}
main();
精彩评论