Tutorials JavaScript Error Handling — try/catch
Ch 50 / 78
Chapter 50 Intermediate 8 min read JavaScript

Error Handling — try / catch

Bugs happen. Network requests fail. Users enter unexpected input. Error handling is what separates fragile scripts from production-ready code. JavaScript provides try, catch, finally, and throw to intercept, respond to, and recover from errors — and lets you define custom Error classes for domain-specific problems.

Advertisement
What you'll learn
The try / catch / finally block structure and when each part runs
Throwing errors manually with throw and the Error constructor
Built-in error types — TypeError, RangeError, SyntaxError and more
Creating custom Error subclasses for your own application errors
Handling errors in async/await and Promise chains
Global error catching with window.onerror and unhandledrejection

Why Error Handling Matters

Without proper error handling, a single unexpected failure can silently crash your entire application — leaving users with a broken page and no feedback. Good error handling means your app fails gracefully: it catches the problem, logs it, shows a helpful message, and keeps running.

Without Error Handling
Errors propagate uncontrolled — one bug breaks everything.
  • Uncaught errors crash the entire JS execution thread
  • Users see nothing — white screen or frozen UI
  • No logging — hard to debug in production
  • Async failures silently disappear (unhandled rejections)
  • Cannot distinguish different error types or respond accordingly
With Error Handling
Errors are caught, classified, and responded to appropriately.
  • App continues running after handled errors
  • Users see friendly, actionable error messages
  • Errors are logged for monitoring and debugging
  • Async errors are always caught with try/catch or .catch()
  • Custom Error classes enable typed, recoverable errors

The try / catch / finally Structure

JavaScript's error handling is built on three keywords that work together. Code that might throw goes inside try. If it throws, execution jumps to catch, which receives the error object. finally always runs — whether an error occurred or not — perfect for cleanup work.

Block anatomy — when each part executes
try
Always runs first. Contains the code that might throw. If no error occurs, catch is skipped entirely and execution continues after the block (or in finally).
catch
Only runs if try throws. Receives the error object — use err.message, err.name, err.stack. You can re-throw if you can't handle the error here.
finally
Always runs — after try succeeds or after catch handles an error. Use it to close connections, hide loading spinners, or release resources. Optional — can be omitted.
throw
Manually raises an error. You can throw any value, but always use new Error("message") (or a subclass) so the catch block gets a proper error object with a stack trace.
JavaScript — try / catch / finally
// ── Basic structure ───────────────────────────────────────
try {
const data = JSON.parse('{ bad json }'); // throws SyntaxError
console.log(data.name); // ← never reached
} catch (err) {
console.error("Caught:", err.name); // "SyntaxError"
console.error("Message:", err.message); // "Unexpected token b..."
console.error("Stack:", err.stack); // full stack trace
} finally {
console.log("This always runs"); // cleanup here
}

// ── finally for cleanup — loading spinner example ─────────
async function loadData() {
showSpinner(); // start loading UI
try {
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
renderData(data);
} catch (err) {
showErrorBanner(err.message);
} finally {
hideSpinner(); // always hide — whether success or error
}
}

// ── catch is optional if you only need finally ────────────
try {
riskyOperation();
} finally {
cleanup(); // runs even if error propagates upward
}

The throw Statement

throw lets you raise your own errors — enforcing preconditions, signalling invalid input, or converting low-level failures into meaningful domain errors. You can technically throw any value, but always throw an Error object so the receiver gets a .message, .name, and stack trace.

throw flow — what happens after you throw
1
throw new Error("msg") is executed
Execution of the current function stops immediately at the throw statement.
2
JavaScript unwinds the call stack
It looks for the nearest enclosing try block — searching up through every caller in the stack.
3a
Matching try/catch found — error is caught
The catch block runs with the error object. finally runs after, then execution continues normally.
3b
No handler found — uncaught error
The error propagates to the browser/Node.js runtime, logs to the console, and halts further JS execution.
JavaScript — throw & Re-throw
// ── Validate input — throw on bad data ────────────────────
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers");
}
if (b === 0) {
throw new RangeError("Cannot divide by zero");
}
return a / b;
}

try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws RangeError
} catch (err) {
console.error(err.name, err.message); // RangeError: Cannot divide by zero
}

// ── Re-throwing — handle only what you can ────────────────
function processData(raw) {
try {
return JSON.parse(raw);
} catch (err) {
if (err instanceof SyntaxError) {
throw new Error(`Invalid JSON input: ${err.message}`); // wrap with context
}
throw err; // re-throw unexpected errors unchanged
}
}

Built-in Error Types

JavaScript ships with several specialised Error subclasses. Use instanceof inside catch to handle each type differently, or check err.name as a string comparison.

Error
The base class. Use it for general-purpose errors or as the parent for custom subclasses.
TypeError
Wrong type — calling a non-function, accessing a property on null or undefined.
RangeError
Value out of allowed range — array length < 0, invalid toFixed() argument.
ReferenceError
Accessing an undeclared variable — console.log(foo) when foo was never defined.
SyntaxError
Invalid JavaScript syntax — usually from JSON.parse() or eval() with bad input.
URIError
Bad URI encoding — malformed argument to decodeURIComponent().
EvalError
Rarely used today. Historical error from misuse of eval().
AggregateError
Wraps multiple errors — thrown by Promise.any() when all promises reject.
JavaScript — Identifying Error Types with instanceof
try {
riskyOperation();
} catch (err) {

if (err instanceof TypeError) {
console.error("Type problem:", err.message);
// e.g. fix the type and retry

} else if (err instanceof RangeError) {
console.error("Value out of range:", err.message);

} else if (err instanceof SyntaxError) {
console.error("Malformed data — cannot parse");

} else if (err instanceof ReferenceError) {
console.error("Undefined variable:", err.message);

} else {
throw err; // unknown — re-throw for the caller
}
}

// ── Error properties every error object has ───────────────
const err = new TypeError("Expected a string");
console.log(err.name); // "TypeError"
console.log(err.message); // "Expected a string"
console.log(err.stack); // stack trace string (V8/Node.js)

Custom Error Classes

For real applications you'll want to define your own error types — so callers can use instanceof to distinguish an AuthError from a NetworkError from a ValidationError. Extend the built-in Error class and always call super(message) in the constructor.

JavaScript — Custom Error Classes
// ── Base application error ────────────────────────────────
class AppError extends Error {
constructor(message, code) {
super(message); // sets .message and .stack
this.name = "AppError";
this.code = code; // custom property
}
}

// ── Domain-specific subclasses ────────────────────────────
class ValidationError extends AppError {
constructor(field, message) {
super(message, "VALIDATION_ERROR");
this.name = "ValidationError";
this.field = field; // which field failed
}
}

class AuthError extends AppError {
constructor(message) {
super(message, "AUTH_ERROR");
this.name = "AuthError";
}
}

class NetworkError extends AppError {
constructor(message, status) {
super(message, "NETWORK_ERROR");
this.name = "NetworkError";
this.status = status; // HTTP status code
}
}

// ── Using custom errors ───────────────────────────────────
async function login(email, password) {
if (!email.includes("@")) {
throw new ValidationError("email", "Invalid email address");
}
const res = await fetch("/api/login", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" }
});
if (res.status === 401) throw new AuthError("Invalid credentials");
if (!res.ok) throw new NetworkError("Server error", res.status);
return res.json();
}

// ── Typed catch block ─────────────────────────────────────
try {
await login("bad-email", "pass");
} catch (err) {
if (err instanceof ValidationError) {
highlightField(err.field, err.message);
} else if (err instanceof AuthError) {
showToast("Wrong email or password");
} else if (err instanceof NetworkError) {
showToast(`Server error (${err.status})`);
} else {
throw err; // unexpected — propagate
}
}
Advertisement

Error Handling in async / await & Promises

Errors in asynchronous code need their own strategies. With async/await, wrap the entire async body in try/catch — it catches both synchronous throws and rejected Promises. With .then() chains, always end with .catch(). An unhandled Promise rejection is a silent bug — always handle it.

JavaScript — Async Error Handling Patterns
// ── async/await — try/catch is the cleanest approach ──────
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new NetworkError("Failed to fetch user", res.status);
const user = await res.json();
return user;
} catch (err) {
logError(err); // send to monitoring service
throw err; // re-throw for the caller to handle UI
}
}

// ── Promise chain — always attach .catch() ────────────────
fetch("/api/data")
.then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); })
.then(data => renderData(data))
.catch(err => showError(err.message)); // catches any throw above

// ── Danger: swallowing errors silently ────────────────────
async function badPattern() {
try {
await doSomething();
} catch (err) {
// ❌ empty catch — error is silently ignored!
}
}

// ── Better pattern: at minimum, log the error ─────────────
async function goodPattern() {
try {
await doSomething();
} catch (err) {
console.error("[goodPattern] unexpected error:", err); // ✅ at minimum log
throw err; // and re-throw for caller
}
}

Global Error Handlers

Even with careful local error handling, some errors slip through. Register global handlers as a safety net — to log unexpected errors to a monitoring service (e.g. Sentry) before the user sees a broken page. These do not replace proper local handling — they are the last line of defence.

JavaScript — Global Error Handlers
// ── window.onerror — catches synchronous uncaught errors ──
window.onerror = function(message, source, lineno, colno, error) {
console.error("Uncaught error:", { message, source, lineno, error });
sendToMonitoring({ message, source, lineno, stack: error?.stack });
return true; // prevents browser's default error UI
};

// ── unhandledrejection — catches unhandled Promise rejections
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise rejection:", event.reason);
sendToMonitoring({ type: "unhandledrejection", reason: event.reason });
event.preventDefault(); // suppresses console warning
});

// ── rejectionhandled — fires when a rejection IS later handled
window.addEventListener("rejectionhandled", (event) => {
console.log("Previously unhandled rejection is now handled");
});

// ── Node.js equivalents ───────────────────────────────────
process.on("uncaughtException", (err) => {
console.error("Uncaught exception:", err);
process.exit(1); // must exit — process is in undefined state
});

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

Quick Reference — Error Object Properties & Patterns

Property / Pattern Type Description
err.name string Error type name — "TypeError", "RangeError", "ValidationError", etc.
err.message string Human-readable description passed to the Error constructor
err.stack string Full stack trace string — invaluable for debugging (V8 / Node.js)
err.cause any ES2022 — wrap an original error: new Error("msg", { cause: originalErr })
err instanceof Error boolean Checks error type — works across custom subclasses too
throw new Error(msg) — Always use Error objects — never throw strings or plain objects
try / catch / finally — Core block structure — finally runs even if catch re-throws
.catch(handler) Promise Required at the end of every Promise chain — never leave a chain without it
unhandledrejection event Global safety net for Promise rejections — use for monitoring/logging only
Empty catch {} anti-pattern Never silently swallow errors — at minimum console.error(err) or re-throw

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel