Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Error

From MDC


目录

[编辑] Summary

Core Object

Represents a runtime error.

[编辑] Created by

The Error constructor:

new Error()
new Error(message)

Runtime errors also result in a new Error object being created and thrown.

[编辑] Parameters

message 
Error message.

[编辑] Description

Besides the base Error, there are six other core error types in JavaScript 1.5:

  • EvalError: raised when an error occurs executing code in eval()
  • RangeError: raised when a numeric variable or parameter is outside of its valid range
  • ReferenceError: raised when de-referencing an invalid reference
  • SyntaxError: raised when a syntax error occurs while parsing code in eval()
  • TypeError: raised when a variable or parameter is not a valid type
  • URIError: raised when encodeURI() or decodeURI() are passed invalid parameters

[编辑] Properties

  • constructor: Specifies the function that creates an object's prototype.
  • description: Error description/message (IE only).
  • fileName: Path to file that raised this error (Mozilla only).
  • lineNumber: Line number in file that raised this error (Mozilla only).
  • message: Error message.
  • name: Error name.
  • number: Error number (IE only).
  • prototype: Allows the addition of properties to an Error object.
  • stack: Stack trace (Mozilla only).

[编辑] Examples

[编辑] Example: Throwing a generic error

Usually you create an Error object with the intention of raising it using the throw keyword. You can handle the error using the try...catch construct:

try {
    throw new Error("Whoops!");
} catch (e) {
    alert(e.name + ": " + e.message);
}

[编辑] Example: Handling a specific error

You can choose to handle only specific error types by testing the error type with the error's constructor property or, if you're writing for modern JavaScript engines, instanceof keyword:

try {
    foo.bar();
} catch (e) {
    if (e instanceof EvalError) {
        alert(e.name + ": " + e.message);
    } else if (e instanceof RangeError) {
        alert(e.name + ": " + e.message);
    }
    // ... etc
}

[编辑] See also