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 Class | Trigger Scenario | Example |
|---|---|---|
Error | Base generic error class | throw new Error("Something went wrong"); |
TypeError | Operation on wrong data type or null/undefined | null.toUpperCase() |
ReferenceError | Accessing a non-existent or TDZ variable | console.log(undefinedVar) |
SyntaxError | Invalid JavaScript or malformed JSON | JSON.parse("invalid{") |
RangeError | Value outside allowable numeric range | new 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);
});Related Topics
JavaScript Async and Await
Mastering async/await syntax: synchronous-style asynchronous code, sequential vs parallel execution, and error handling with try/catch.
Document Object Model (DOM) Basics
Interacting with the browser DOM: querySelector, element creation, textContent vs innerHTML, classList manipulation, and event listeners.