Quick Reference

Concept Description
try...catch...finally Handles runtime errors, ensures cleanup.
throw Manually trigger errors.
Error Object Includes name, message, stack.
Error Types TypeError, ReferenceError, SyntaxError, etc.
Sync Errors Caught by try...catch.
Async Errors Not caught unless inside async function or handled via .catch().

try...catch...finally Syntax

try {
  console.log(x); // ReferenceError: x is not defined
} catch (err) {
  console.error(err.message);
} finally {
  console.log("Cleanup done");
}

Throwing Errors

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

try {
  console.log(divide(10, 0));
} catch (err) {
  console.error(err.message);
}

Built-in Error Types

Type Example
Error throw new Error("Custom error")
SyntaxError eval("foo bar")
ReferenceError console.log(x) (x is undefined)
TypeError null.foo()
RangeError new Array(-1)
URIError decodeURIComponent("%")

Handling Async Errors

Inside async function (try...catch)

async function fetchData() {
  try {
    let res = await fetch("<https://api.example.com/data>");
    let data = await res.json();
    console.log(data);
  } catch (err) {
    console.error("Error:", err);
  }
}

Async errors in callbacks are not caught

try {
  setTimeout(() => { throw new Error("Not caught"); }, 1000);
} catch (err) {
  console.error("Won't be caught:", err);
}

Fix: Handle inside the callback