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