Exception Handling in JavaScript: Using Multiple Exception Handlers - Working with primary error types: defining error types for the JavaScript 1.5 specification
(Page 3 of 5 )
In normal conditions, you may want to set up exception handlers for the most common error types found during the execution of a program. Considering this, JavaScript interpreters that are fully compliant with the 1.5 specification, define six primary error types, categorized in the following list:
EvalError: triggered by the interpreter when the eval() function fails to evaluate its argument.
RangeError: triggered by the interpreter when a numeric variable exceeds its allowed range.
ReferenceError: triggered by the interpreter when an invalid reference is used (applicable to data containers as well as methods or functions).
SyntaxError: triggered when the interpreter finds a syntax error while parsing JavaScript code.
TypeError: triggered when the type of a variable is incorrect.
URIError: triggered when the encodeURI() and decodeURI() functions receive invalid arguments.
As you can see, the above list provides enough support to handle common errors in a very efficient way. Even in the case where you might want to set up an exception handler for an error not contemplated on the list, JavaScript will allow you to create your own custom exception and implement the corresponding handler, by using the built-in Error constructor.
So far, I’ve coded some primitive examples of exception handlers, which only generated simple error messages without giving more descriptive information on the error that occurred. However, there is more good news in the JavaScript universe. In addition to providing support for primary error types, JavaScript also offers two predefined properties of the Error object generated by an exception, the “name” and “message” properties.
Considering JavaScript the exception capabilities just described, let’s turn our attention to building an example for seeing how they can be properly implemented within a simple program.
Next: A practical example: trapping multiple error types >>
More JavaScript Articles
More By Alejandro Gervasio