AI Workshop: learn to build apps with AI →
Errors and exceptions: Types of errors

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Error

This is the generic error, and it’s the one all the other error objects inherit from. You will never see an instance of Error directly, but rather JavaScript throws one of the other error types listed below, which all inherit from Error.

It contains two properties:

  • message: the error description, a human-readable message that should explain what error happened
  • name: the type of error that occurred (assumes the value of the specific error object name, for example, TypeError or SyntaxError)

and provides just one method, toString(), which is responsible for generating a meaningful string from the error, which can be used to print it to screen.

RangeError

A RangeError will fire when a numeric value is not in its range of allowed values.

The simplest example is when you set an array length to a negative value:

[].length = -1 //RangeError: Invalid array length

or when you set it to a number higher than 4294967295

[].length = 4294967295 //4294967295
[].length = 4294967296 //RangeError: Invalid array length

(this magic number is specified in the JavaScript spec as the maximum range of a 32-bit unsigned integer, equivalent to Math.pow(2, 32) - 1)

Here are the most common range errors:

ReferenceError

A ReferenceError indicates that an invalid reference value has been detected: a JavaScript program is trying to read a variable that does not exist.

dog //ReferenceError: dog is not defined
dog = 2 //ReferenceError: dog is not defined

Be aware that the above statement will create a dog variable on the global object if not run in strict mode.

Here are the most common reference errors:

SyntaxError

A SyntaxError is raised when invalid syntax is found in a program.

Here are some examples of code that generates a syntax error.

A function statement without a name:

function() {
  return 'Hi!'
}
//SyntaxError: function statement requires a name

Missing comma after an object property definition:

const dog = {
  name: 'Roger'
  age: 5
}
//SyntaxError: missing } after property list

Here are the most common syntax errors:

TypeError

A TypeError happens when a value has a type that’s different from the one expected.

The simplest example is trying to invoke a number:

1() //TypeError: 1 is not a function

Here are the most common type errors:

URIError

This error is raised when calling one of the global functions that work with URIs:

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()

and passing an invalid URI.

Lessons in this unit:

0: Introduction
1: ▶︎ Types of errors
2: Creating exceptions
3: Handling exceptions
4: Finally
5: Nested try blocks