Error Handling

Gracefully handle the unexpected. Build resilient code.

try / catch / finally

The fundamental error-handling structure.

try {
  const data = JSON.parse("invalid json");
} catch (error) {
  console.error(error.message);
  // "Unexpected token i in JSON"
} finally {
  console.log("Always runs");
}

try wraps risky code. catch receives the error. finally always executes.

1 / 2

Built-in Error Types

JavaScript has specific error classes.

TypeErrornull.toString()Wrong type operation
ReferenceErrorconsole.log(x)Variable doesn't exist
SyntaxErroreval('{')Invalid code structure
RangeErrornew Array(-1)Value out of range
URIErrordecodeURI('%')Bad URI encoding

Custom Errors

Create domain-specific error classes.

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

class NotFoundError extends Error {
  constructor(resource) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
    this.status = 404;
  }
}

// Usage:
throw new ValidationError("email", "Invalid format");

Best Practices

Patterns for production code.

// ✓ Fail fast with meaningful messages
function divide(a, b) {
  if (b === 0) {
    throw new RangeError("Division by zero");
  }
  return a / b;
}

Validate inputs early and throw descriptive errors.

1 / 3