Classic JS Tutorial | JS in VS 2026 | JS Examples | jQuery
⚡ Lesson 13 of 30

Error Handling – try/catch

Write robust programs that handle runtime errors gracefully using try, catch, finally, and custom errors.

try / catch

try {
  const data = JSON.parse("{ invalid json }");
} catch (error) {
  console.error("Caught:", error.message);
}

finally

finally always runs — useful for cleanup (closing files, hiding spinners):

function fetchData(url) {
  showSpinner(true);
  try {
    // ... fetch logic
  } catch (e) {
    console.error(e);
  } finally {
    showSpinner(false); // always runs
  }
}

Throwing Errors

Use throw to signal error conditions in your own code:

function divide(a, b) {
  if (b === 0) throw new Error("Division by zero!");
  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (e) {
  console.error(e.message); // "Division by zero!"
}

Custom Error Classes

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

try {
  throw new ValidationError("email", "Invalid email address");
} catch (e) {
  if (e instanceof ValidationError) {
    console.log(`${e.field}: ${e.message}`);
  }
}

Error Types

JavaScript has several built-in error types:

// ReferenceError — variable not defined
try { console.log(x); } catch(e) { console.log(e.name); }

// TypeError — wrong type
try { null.toString(); } catch(e) { console.log(e.name); }

// RangeError — value out of range
try { new Array(-1); } catch(e) { console.log(e.name); }
← Lesson 12🏠 HomeLesson 14 →