programming foundations20 min

Error Handling

Catching and recovering from errors gracefully

0/9Not Started

Why This Matters

Every program encounters errors — invalid input, missing files, network failures, division by zero. The difference between a program that crashes and one that handles problems gracefully is error handling. Learning to anticipate, catch, and recover from errors is essential for writing robust software.

Without error handling, a single unexpected value can crash your entire application. With it, you can show helpful messages, retry operations, or fall back to defaults.

Define Terms

Visual Model

Code runs
Error occurs?
Continue
catch block
Handle error
finally block
Program continues
no
yes

The full process at a glance. Click Start tour to walk through each step.

try/catch/finally: errors are caught and handled instead of crashing the program.

Code Example

Code
// Basic try/catch
try {
  const data = JSON.parse("not valid json");
} catch (error) {
  console.log("Parse failed:", error.message);
}
// Output: Parse failed: Unexpected token ...

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

try {
  console.log(divide(10, 2));  // 5
  console.log(divide(10, 0));  // throws!
} catch (error) {
  console.log("Caught:", error.message);
}
// Output: 5, then Caught: Cannot divide by zero

// finally always runs
try {
  console.log("trying...");
  throw new Error("oops");
} catch (e) {
  console.log("caught:", e.message);
} finally {
  console.log("cleanup done");
}
// trying... caught: oops cleanup done

// Error types
try {
  null.property;       // TypeError
} catch (e) {
  console.log(e.constructor.name, e.message);
}

Interactive Experiment

Try these exercises:

  • Write a safeParse function that wraps JSON.parse in try/catch and returns null on failure.
  • Throw a custom error when a function receives a negative number.
  • Use finally to always print "Done" after an operation, whether it succeeds or fails.
  • What happens if you throw inside a catch block? Can you nest try/catch?
  • Try catching different error types: TypeError, RangeError, SyntaxError.

Quick Quiz

Coding Challenge

Safe Division

Write a function called `safeDivide` that takes two numbers and returns their division result. If the divisor is 0, it should return the string 'Error: Division by zero' instead of throwing. If either argument is not a number, return 'Error: Invalid input'.

Loading editor...

Real-World Usage

Error handling is everywhere in production code:

  • API requests: Network calls can fail. try/catch with fetch lets you show "retry" buttons instead of blank screens.
  • User input: Parsing dates, numbers, and JSON from user input always needs validation and error handling.
  • File operations: Reading/writing files can fail (permissions, disk full, file not found).
  • Database queries: Connections drop, queries timeout, constraints are violated.
  • Third-party libraries: External code can throw unexpected errors that you need to catch at boundaries.

Connections