Error Handling
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
- Control FlowProgramming Fundamentals
Error handling (try/catch, error returns) is a specialized, non-local form of control flow — you need ordinary branching and the call stack concept before the 'jump to the nearest handler' behavior makes sense as a variant of it.
Helps
- Functions & ScopeProgramming Fundamentals
Exceptions unwind through function call frames; understanding the call stack from functions-and-scope makes it clear what 'unwinding' actually removes.
Unlocks
Used in
- try/catch/finally in JavaScript, Java, Python, and most mainstream languages
- Result/Option types (Rust, Swift) as an alternative, non-exception approach to the same problem
- HTTP error status codes and API error response conventions
- Retry and circuit-breaker patterns in distributed systems clients
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
- I can explain what 'unwinding the call stack' means when an exception is thrown
- I can design distinct error cases instead of one generic catch-all error
- I can decide between exceptions and explicit error-return values for a given situation
- I can write a try/catch/finally block and explain exactly when each part executes