JavaScript has a built-in error object that supplies information about an error when it occurs.
The error object contains two important properties: name
and message
.
Property |
Description |
name |
Gets or sets the name of the error. |
message |
Gets or sets the error message (a string). |
The name property of an error can return six different values:
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 |
An EvalError signifies an issue with the eval() function.
In newer versions of JavaScript, EvalError is no longer thrown. Instead, a SyntaxError is used. |
A RangeError is thrown when a number falls outside the acceptable range of values.
For example, you cannot set the number of significant digits of a number to 500.
let num = 1; try { num.toPrecision(500); // A number cannot have 500 significant digits } catch(err) { document.getElementById(“demo”).innerHTML = err.name; } |
A ReferenceError is thrown if you attempt to reference a variable that has not been declared.
let x = 5; try { x = y + 1; // y cannot be used (referenced) } catch(err) { document.getElementById(“demo”).innerHTML = err.name; } |
A SyntaxError is thrown if you attempt to execute code that contains a syntax error.
try { eval(“alert(‘Hello)”); // Missing ‘ will produce an error } catch(err) { document.getElementById(“demo”).innerHTML = err.name; } |
A TypeError is thrown when an operand or argument is not compatible with the expected type for an operator or function.
let num = 1; try { num.toUpperCase(); // You cannot convert a number to upper case } catch(err) { document.getElementById(“demo”).innerHTML = err.name; } |
A URIError
is thrown if illegal characters are used in a URI function.
try { decodeURI(“%%%”); // You cannot URI decode percent signs } catch(err) { document.getElementById(“demo”).innerHTML = err.name; } |
Mozilla and Microsoft define some non-standard error object properties: fileName (Mozilla) lineNumber (Mozilla) columnNumber (Mozilla) stack (Mozilla) description (Microsoft) number (Microsoft) Avoid using these properties on public websites, as they may not be supported across all browsers. |