Skip to main content
⚑ OpenDevDocs
JavaScript
programmingjavascriptGuideBeginner

JavaScript Error Handling (try, catch, throw, Error)

Mastering error handling in JavaScript: try/catch/finally blocks, standard Error subclasses (TypeError, SyntaxError), custom error classes, and unhandled rejections.

Verified: 2026-09-30
Tested on:node 22.x
Platforms:
webnode
#javascript#errors#try-catch#exceptions#debugging

JavaScript Error Handling (try, catch, throw, Error)

Robust error handling ensures applications degrade gracefully and log actionable diagnostics when runtime failures occur.


1. The try...catch...finally Statement

try {
  // Code that may throw an exception
  const data = JSON.parse(rawString);
  processData(data);
} catch (error) {
  // Executed if an error was thrown inside try block
  console.error("Parsing failed:", error.name, error.message);
} finally {
  // Always executed, regardless of whether an error was thrown
  cleanupTemporaryResources();
}

2. Standard Built-in Error Types

Error ClassTrigger ScenarioExample
ErrorBase generic error classthrow new Error("Something went wrong");
TypeErrorOperation on wrong data type or null/undefinednull.toUpperCase()
ReferenceErrorAccessing a non-existent or TDZ variableconsole.log(undefinedVar)
SyntaxErrorInvalid JavaScript or malformed JSONJSON.parse("invalid{")
RangeErrorValue outside allowable numeric rangenew Array(-1)

3. Creating Custom Error Classes

Subclassing Error allows you to add custom HTTP status codes or error tags:

export class ApiError extends Error {
  constructor(message, statusCode, code = "INTERNAL_ERROR") {
    super(message);
    this.name = "ApiError";
    this.statusCode = statusCode;
    this.code = code;
  }
}

// Throwing custom error:
throw new ApiError("User account suspended", 403, "ACCOUNT_SUSPENDED");

4. Catching Global Unhandled Errors

In Node.js:

process.on("unhandledRejection", (reason, promise) => {
  console.error("Unhandled Rejection at:", promise, "reason:", reason);
});

process.on("uncaughtException", (error) => {
  console.error("Uncaught Exception:", error);
  process.exit(1); // Exit safely
});

In Browser:

window.addEventListener("error", (event) => {
  console.error("Global script error:", event.error);
});

On this page