Error Handling

Difficulty
Importance

The problem

Operations fail — files are missing, networks time out, input is malformed — and a program needs a disciplined way to detect failure and hand control to code equipped to deal with it, rather than either crashing everywhere or silently continuing with garbage data.

Why now

Control flow gives branching and looping, but ordinary branches assume the code deciding what to do next is right next to the code that might fail. Error handling is control flow's answer to failures that need to jump out of many levels at once — back up to whichever caller actually knows what to do.

Mental model

An exception is a special kind of return that skips every normal return path and unwinds the call stack until it finds a handler that says 'I know what to do with this.' try/catch is a branch, just one whose condition is 'did anything below this line throw' instead of an explicit if.

Requires

Helps

Unlocks

Used in

Projects

  • Write a function that reads and parses a file, handling 'file not found' and 'invalid format' as two distinct, clearly-labeled error cases
  • Refactor a chain of error-code-checking if-statements into try/catch, and discuss which is more readable and why

Examples

  • try { JSON.parse(input) } catch (e) { /* handle malformed input here, far from where it was parsed */ }
  • A network client that catches a timeout, retries twice, then surfaces a clear error to the caller

Resources

Mastery checklist