JavaScript has a built in error object that provides error information when an error occurs.

The error object provides two useful properties: name and message.


Error Object Properties

Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)
 

Error Name Values

Six different values can be returned by the error name property:

Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred

The six different values are described below.
 

Eval Error

An EvalError indicates an error in the eval() function.

Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.


Range Error

RangeError is thrown if you use a number that is outside the range of legal values.

For example: You cannot set the number of significant digits of a number to 500.

Example

var num = 1;
try {
  num.toPrecision(500);   // A number cannot have 500 significant digits
}
catch(err) {
  document.getElementById("demo").innerHTML = err.name;
}
 

Reference Error

ReferenceError is thrown if you use (reference) a variable that has not been declared:

Example

var x;
try {
  x = y + 1;   // y cannot be referenced (used)
}
catch(err) {
  document.getElementById("demo").innerHTML = err.name;
}
 

Syntax Error

SyntaxError is thrown if you try to evaluate code with a syntax error.

Example

try {
  eval("alert('Hello)");   // Missing ' will produce an error
}
catch(err) {
  document.getElementById("demo").innerHTML = err.name;
}
 

Type Error

TypeError is thrown if you use a value that is outside the range of expected types:

Example

var num = 1;
try {
  num.toUpperCase();   // You cannot convert a number to upper case
}
catch(err) {
  document.getElementById("demo").innerHTML = err.name;
}
 

URI (Uniform Resource Identifier) Error

URIError is thrown if you use illegal characters in a URI function:

Example

try {
  decodeURI("%%%");   // You cannot URI decode percent signs
}
catch(err) {
  document.getElementById("demo").innerHTML = err.name;
}
 

Non-Standard Error Object Properties

Mozilla and Microsoft defines some non-standard error object properties:

fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)

Do not use these properties in public web sites. They will not work in all browsers.



Practice Excercise Practice now