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.

// put your code here that may experience a runtime error/exception, i will show division by zero in this example
var x = 1;
if(e instanceof Error){
alert(‘an error has occurred:name=’ + + ‘|message=’ + e.message);
} else {
alert(‘an unknown exception has occurred’);
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



Leave a Reply