Advanced Error-Handling Techniques (try, throw, catch)

Calling functions and testing return values is acceptable in an application, but it isn’t optimal. A better approach is to make function calls and use objects without continuously testing for results, and then include exception handling at the end of the script to catch whatever errors happen.

Beginning with JavaScript 1.5, the use of try...catch...finally was incorporated into the JavaScript language. The try statement delimits a block of code that’s enclosed in the exception- handling mechanism. The catch statement is at the end of the block; it catches any exception and allows you to process the exception however you feel is appropriate.

The use of finally isn’t required, but it is necessary if there’s some operation that must be performed whether an exception occurs or not. It follows the catch statement, and, combined with the exception-handling mechanism, has the following format:

try {
...
} 
catch (e) {
...
}
finally {
...
}

There are six error types implemented in JavaScript 1.5 engines:

EvalError

Raised by eval when used incorrectly

RangeError

Numeric value exceeds its range

ReferenceError

Invalid reference is used

SyntaxError

Used with invalid syntax

TypeError

Raised when variable is not the type expected

URIError

Raised when encodeURI(  ) or decodeURI(  ) are used incorrectly

Using instanceOf when catching the error lets you know if the error is one of these built-in types. In the following code, a TypeError ...

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.