Lesson 27 / 38

try/catch & Custom Errors

Catching failures gracefully, and defining your own error types.

try / catch / finally

Code in try runs first; if it throws, catch handles it; finally always runs, error or not.

try {
  JSON.parse("{ invalid json");
} catch (err) {
  console.log("Failed:", err.message);
} finally {
  console.log("Always runs");
}

Throwing errors

throw raises an error yourself, stopping normal execution until something catches it.

function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
try {
  divide(10, 0);
} catch (err) {
  console.log(err.message);  // Cannot divide by zero
}

Custom error classes

Extend the built-in Error class to create your own, more descriptive error types.

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}
throw new ValidationError("Invalid input");

Catch specifically

Check err.name or use instanceof to handle different error types differently instead of one generic catch-all.