Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 820927 of Error

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Error
  • Revision title: Error
  • Revision id: 820927
  • Created:
  • Creator: janosch-x
  • Is current revision? No
  • Comment fixed typo: "decodeURl" (w. lowercase L) must be "decodeURI" (w. uppercase i)

Revision Content

{{JSRef("Global_Objects", "Error", "EvalError,InternalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError")}}

Summary

The Error constructor creates an error object. Instances of Error objects are thrown when runtime errors occur. The Error object can also be used as a base objects for user-defined exceptions. See below for standard built-in error types.

Syntax

new Error([message[, fileName[, lineNumber]]])

Parameters

message
Optional. Human-readable description of the error.
fileName {{non-standard_inline}}
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
lineNumber {{non-standard_inline}}
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.

Description

Runtime errors result in new Error objects being created and thrown.

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

Error types

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

{{jsxref("Global_Objects/EvalError", "EvalError")}}
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
{{jsxref("Global_Objects/InternalError", "InternalError")}} {{non-standard_inline}}
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
{{jsxref("Global_Objects/RangeError", "RangeError")}}
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
{{jsxref("Global_Objects/ReferenceError", "ReferenceError")}}
Creates an instance representing an error that occurs when de-referencing an invalid reference.
{{jsxref("Global_Objects/SyntaxError", "SyntaxError")}}
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
{{jsxref("Global_Objects/TypeError", "TypeError")}}
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
{{jsxref("Global_Objects/URIError", "URIError")}}
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.

Properties

{{jsxref("Error.prototype")}}
Allows the addition of properties to Error instances.

Methods

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

Error instances

{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}

Properties

{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}

Methods

{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}

Examples

Example: Throwing a generic error

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

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

Example: Handling a specific error

this should probably be removed You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "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
}

Example: Custom Error Types

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

// Create a new object, that prototypally inherits from the Error constructor.
function MyError(message) {
  this.name = 'MyError';
  this.message = message || 'Default Message';
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

try {
  throw new MyError();
} catch (e) {
  console.log(e.name);     // 'MyError'
  console.log(e.message);  // 'Default Message'
}

try {
  throw new MyError('custom message');
} catch (e) {
  console.log(e.name);     // 'MyError'
  console.log(e.message);  // 'custom message'
}

Specifications

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}} {{Spec2('ES5.1')}}  
{{SpecName('ES6', '#sec-error-objects', 'Error')}} {{Spec2('ES6')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

See also

  • {{jsxref("Error.prototype")}}
  • {{jsxref("Statements/throw", "throw")}}
  • {{jsxref("Statements/try...catch", "try...catch")}}

Revision Source

<div>{{JSRef("Global_Objects", "Error", "EvalError,InternalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError")}}</div>

<h2 id="Summary">Summary</h2>

<p>The <strong><code>Error</code></strong> constructor creates an error object. Instances of <code>Error</code> objects are thrown when runtime errors occur. The <code>Error</code> object can also be used as a base objects for user-defined exceptions. See below for standard built-in error types.</p>

<h2 id="Syntax" name="Syntax">Syntax</h2>

<pre class="syntaxbox">
new Error([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</pre>

<h3 id="Parameters" name="Parameters">Parameters</h3>

<dl>
 <dt><code>message</code></dt>
 <dd>Optional. Human-readable description of the error.</dd>
 <dt><code>fileName</code> {{non-standard_inline}}</dt>
 <dd>Optional. The value for the <code>fileName</code> property on the created <code>Error</code> object. Defaults to the name of the file containing the code that called the <code>Error()</code> constructor.</dd>
 <dt><code>lineNumber</code> {{non-standard_inline}}</dt>
 <dd>Optional. The value for the <code>lineNumber</code> property on the created <code>Error</code> object. Defaults to the line number containing the <code>Error()</code> constructor invocation.</dd>
</dl>

<h2 id="Description" name="Description">Description</h2>

<p>Runtime errors result in new <code>Error</code> objects being created and thrown.</p>

<p>This page documents the use of the <code>Error</code> object itself and its use as a constructor function. For a list of properties and methods inherited by <code>Error</code> instances, see {{jsxref("Error.prototype")}}.</p>

<h3 id="Error_types" name="Error_types">Error types</h3>

<p>Besides the generic <code>Error</code> constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see <a href="/en-US/docs/Web/JavaScript/Guide/Statements#Exception_Handling_Statements">Exception Handling Statements</a>.</p>

<dl>
 <dt>{{jsxref("Global_Objects/EvalError", "EvalError")}}</dt>
 <dd>Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.</dd>
 <dt>{{jsxref("Global_Objects/InternalError", "InternalError")}} {{non-standard_inline}}</dt>
 <dd>Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".</dd>
 <dt>{{jsxref("Global_Objects/RangeError", "RangeError")}}</dt>
 <dd>Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.</dd>
 <dt>{{jsxref("Global_Objects/ReferenceError", "ReferenceError")}}</dt>
 <dd>Creates an instance representing an error that occurs when de-referencing an invalid reference.</dd>
 <dt>{{jsxref("Global_Objects/SyntaxError", "SyntaxError")}}</dt>
 <dd>Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.</dd>
 <dt>{{jsxref("Global_Objects/TypeError", "TypeError")}}</dt>
 <dd>Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.</dd>
 <dt>{{jsxref("Global_Objects/URIError", "URIError")}}</dt>
 <dd>Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.</dd>
</dl>

<h2 id="Properties" name="Properties">Properties</h2>

<dl>
 <dt>{{jsxref("Error.prototype")}}</dt>
 <dd>Allows the addition of properties to <code>Error</code> instances.</dd>
</dl>

<h2 id="Methods" name="Methods">Methods</h2>

<p>The global <code>Error</code> object contains no methods of its own, however, it does inherit some methods through the prototype chain.</p>

<h2 id="Error_instances" name="Error_instances"><code>Error</code> instances</h2>

<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}</div>

<h3 id="Properties_2">Properties</h3>

<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}</div>

<h3 id="Methods_2">Methods</h3>

<div>{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}</div>

<h2 id="Examples" name="Examples">Examples</h2>

<h3 id="Example:_Throwing_a_generic_error" name="Example:_Throwing_a_generic_error">Example: Throwing a generic error</h3>

<p>Usually you create an <code>Error</code> object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:</p>

<pre class="brush: js">
try {
  throw new Error('Whoops!');
} catch (e) {
  alert(e.name + ': ' + e.message);
}
</pre>

<h3 id="Example:_Handling_a_specific_error" name="Example:_Handling_a_specific_error">Example: Handling a specific error</h3>

<p><span class="comment">this should probably be removed</span> You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:</p>

<pre class="brush: js">
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
}
</pre>

<h3 id="Example.3A_Custom_Error_Types">Example: Custom Error Types</h3>

<p>You might want to define your own error types deriving from <code>Error</code> to be able to <code>throw new MyError()</code> and use <code>instanceof MyError</code> to check the kind of error in the exception handler. The common way to do this is demonstrated below.</p>

<div class="warning">
<p>Note that the thrown <code>MyError</code> will report incorrect <code>lineNumber</code> and <code>fileName</code> at least in Firefox.</p>
</div>

<p>See also the <a href="https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript">"What's a good way to extend Error in JavaScript?" discussion on Stackoverflow</a>.</p>

<pre class="brush: js">
// Create a new object, that prototypally inherits from the Error constructor.
function MyError(message) {
  this.name = 'MyError';
  this.message = message || 'Default Message';
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

try {
  throw new MyError();
} catch (e) {
  console.log(e.name);     // 'MyError'
  console.log(e.message);  // 'Default Message'
}

try {
  throw new MyError('custom message');
} catch (e) {
  console.log(e.name);     // 'MyError'
  console.log(e.message);  // 'custom message'
}
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>ECMAScript 1st Edition.</td>
   <td>Standard</td>
   <td>Initial definition. Implemented in JavaScript 1.1.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.11', 'Error')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-error-objects', 'Error')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also" name="See_also">See also</h2>

<ul>
 <li>{{jsxref("Error.prototype")}}</li>
 <li>{{jsxref("Statements/throw", "throw")}}</li>
 <li>{{jsxref("Statements/try...catch", "try...catch")}}</li>
</ul>
Revert to this revision