Error Handling

Catching an error prevents the execution from halting as a result of the error. Errors are caught within try{...} and handled in catch(e){...} (the (e) clause has become optional for catch.) The finally{...} clause will always be executed, even if there is no error.

This example tries to call a function that is not defined. The resulting error is captured by the error object err.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
  try {
    asdd(5);
  } catch (err) {
    document.write(err.message);
  } finally {
    document.write(".");
  }
  document.write(" program not halted.");
</script>
</body>
</html>

asdd is not defined. program not halted.
We can throw our own errors. Uncaught errors halt the program.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
  try {
    var a = 0;
    if (a == 0) throw "Division by zero.";
    document.write(5 / a);
  } catch (err) {
    document.write(err);
  }
  throw "MyError"; // program halted here
  document.write("program halted.");
</script>
</body>
</html>

Division by zero.

Seven Objects inherit from Error: EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError. The inherited properties are: .message, .name, .fileName, .lineNumber, .columnNumber, and .stack.


try {
  var a = undefinedVariable;
} catch (e) {
  console.log(e instanceof ReferenceError);
  console.log(e.message);
  console.log(e.name);
  console.log(e.fileName);
  console.log(e.lineNumber);
  console.log(e.columnNumber);
  console.log(e.stack);
}

true undefinedVariable is not defined ReferenceError MyFile/1 2 6 @ MyFile/2:2:7

When an error is thrown in response to another (eg. inside a catch block, while handling a lower-level failure), ECMAScript 2022 lets you record that original error using the cause option, the second argument accepted by the Error constructor (and its subtypes): new Error(message, {cause}). The original error is then available as the new error's .cause property, giving a traceable chain instead of losing the root cause.


function loadConfig() {
  try {
    JSON.parse('{ bad json');
  } catch (err) {
    throw new Error('Could not load configuration.', {cause: err});
  }
}

try {
  loadConfig();
} catch (e) {
  console.log(e.message);
  console.log(e.cause.name);
}

Could not load configuration. SyntaxError

Error.isError(value), added in ECMAScript 2026, reliably tests whether value is an Error (of any built-in or custom subtype). Unlike 'value instanceof Error', it also correctly recognizes errors created in a different realm (eg. a different iframe or worker, which has its own separate Error constructor), where 'instanceof' would incorrectly return false.


console.log(Error.isError(new TypeError('x')));
console.log(Error.isError({message: 'x'}));   // not really an Error
console.log(Error.isError('x'));

true false false