Javascript try/catch/finally

I’ve found that many developers (including myself) that have been coding javascript for some time don’t realize that javascript added the try/catch pattern from Java quite a while ago and that all modern browsers support it.

Here’s the standard pattern, the ‘finally’ of course is optional for when you require it.

try{
// put your code here that may experience a runtime error/exception, i will show division by zero in this example
var x = 1;
alert(x/0);
}
catch(e){
if(e instanceof Error){
alert(‘an error has occurred:name=’ + e.name + ‘|message=’ + e.message);
} else {
alert(‘an unknown exception has occurred’);
}
}
finally{
alert(‘now we are done’);
}

A little more on this… like in Java, there are types of Errors, and you can rely upon ‘instanceof’ to determine them appropriately, here are a few of the common types in JavaScript 1.5:

  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

REFERENCE:
http://www.devarticles.com/c/a/JavaScript/Exception-Handling-in-JavaScript-Using-Multiple-Exception-Handlers/

Cheers

Custom JavaScript error notification

Debugging JavaScript errors is a time-consuming effort requiring keen eyes and a sharp mind.

MSIE typically only gives a cryptic ‘Object Expected’ error message and little more (even with the Microsoft Script Debugger installed!).

Some tools like FireBug and the Venkman debugger (both for Mozilla/Firefox) help in this matter, but often it helps to have an alert when an issue occurs.

Here’s a simple implementation that I’ve found useful…

[script type=”text/javascript”]
window.onerror=myErrorHandler;

function myErrorHandler(msg,url,l){
var txt=”There was an error on this page.\n”;
txt+=”Error: ” + msg + “\n”;
txt+=”URL: ” + url + “\n”;
txt+=”Line: ” + l + “\n\n”;
txt+=”Click OK to continue.\n\n”;
alert(txt); return true; }
[/script]

REFERENCES:

That’s it….