There are four major error types in programming: compile errors,
logic errors, input/validation errors, and runtime errors. Error
catching in code is usually limited to the latter two types. It would be
nice if you could handle your own logic errors at runtime, but sadly,
there is no such code construct yet. As for syntax errors, an
interpreted language like JavaScript won't catch those until the script
is loaded into and read by the browser. While you normally can't catch
syntax errors, as we'll see shortly, there are times that you can.
Today's article will discuss the syntax error, along with two other
error types, while the next installment will cover the remaining three.
The Six JavaScript Error Types
The JavaScript 1.5 specification defines six primary error types, as follows:
- EvalError: Raised when the eval() functions is used in an incorrect manner.
- RangeError: Raised when a numeric variable exceeds its allowed range.
- ReferenceError: Raised when an invalid reference is used.
- SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
- TypeError: Raised when the type of a variable is not as expected.
- URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.
The Error.name Property
The benefit of having all the different error types is that you can
pinpoint more accurately what kind of error you're dealing with. This is
done using the Error.name property because JavaScript's loose typing
doesn't support specifying which type you want to catch as you would in
Java:
catch(ArrayIndexOutOfBoundsException e) {}
In JavaScript, you have to use an if statement within a single "catch" block:
try {
execute this block
} catch (err) {
if (error.name === 'RangeError')
{
do this
}
else if (error.name === 'ReferenceError')
{
do this
}
else
{
do this for more generic errors
}
}
fonte: http://www.htmlgoodies.com/html5/javascript/handling-javascript-errors-by-type.html#fbid=hrLkQ1Fzytw
0 comentários:
Postar um comentário