Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Error and exception handling

Error handling lets you respond to exceptions without mixing them with a function's normal result. Learn throw, try, catch, and finally, and distinguish synchronous exceptions from Promise rejections.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

throw new Error(message);
try {
  operation();
} catch (error) {
  handle(error);
} finally {
  cleanup();
}

An exception interrupts the current execution path. throw can throw any value, but use Error objects or their subtypes: they provide name and message properties. TypeError describes an inappropriate type or an invalid operation, while RangeError describes a value outside an allowed range. Merely calling new Error(message) creates an object without throwing it.

try surrounds operations that may throw; catch (error) receives the thrown value, including one from a synchronously called function. Execution does not resume at the interrupted statement. Handle only errors you can meaningfully address; rethrow others with throw error. A syntax error that prevents parsing of the same script cannot be caught by that script's catch.

finally executes when control leaves try or catch, including through return or an exception. Use it for cleanup. Avoid return and throw inside it because they can replace an earlier result or exception. A try statement requires catch, finally, or both.

A synchronous try does not catch a later Promise rejection merely because the promise was created inside its block. Use await in try inside an async function, or attach .catch(handler). The example uses basic exception mechanisms available since ECMAScript 3; Promise comes from ECMAScript 2015 and async/await from ECMAScript 2017. It requires no Web APIs apart from the environment-provided console.log; a Node.js version alone does not establish browser support.

Examples

function requirePositive(value) {
  if (!(value > 0)) {
    throw new RangeError("value must be positive");
  }
  return value;
}

try {
  console.log(requirePositive(-1));
} catch (error) {
  if (!(error instanceof RangeError)) {
    throw error;
  }
  console.log(error.name + ": " + error.message);
} finally {
  console.log("finished");
}

Result

RangeError: value must be positive
finished

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources