Exception handling
Exception handling
- An exception is an error during execution — divide by zero, file not found, bad input.
- Exception handling lets a program detect it and respond gracefully instead of crashing.
- It keeps the normal code clean and separate from the error handling.
Why it matters
- Real programs face errors that can't be prevented up front (files moved, networks down, bad input).
- Without it, every operation would need its own
IFcheck, cluttering the code. - It separates the normal flow from the error handling, so the main path reads cleanly.
Practice
An exception is:
Exceptions are run-time problems (divide by zero, file not found) that handling lets you respond to gracefully.
The TRY / EXCEPT / FINALLY pattern
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", line
CLOSEFILE "data.txt"
EXCEPT FileNotFound
OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
OUTPUT "Sorry, error reading the file."
ENDTRY
- The TRY block holds code that might fail; the first matching EXCEPT runs.
- A FINALLY block runs whether or not an exception happened — perfect for cleanup (closing files).
Practice
The TRY block contains:
TRY wraps the risky code; if it fails, the first matching EXCEPT handler runs.
Practice
A FINALLY block:
FINALLY always runs, making it ideal for cleanup such as closing files.
Raising and where to handle
- A subroutine that detects an error can RAISE an exception for the caller to handle:
IF b = 0 THEN RAISE DivideByZero
- Handle it close to the error if the response is simple (a message, a retry), or higher up the call stack if only the outer code knows what to do.
- Don't swallow exceptions silently — at least log them, or debugging becomes impossible.
Practice
A subroutine uses RAISE to:
RAISE throws an exception up to the caller, which can catch it with EXCEPT.
Practice
Why should you not "swallow" exceptions silently?
Silently ignoring exceptions hides real problems; always handle or at least log them.
You've got it
Key idea
- an exception is a run-time error; handling it avoids a crash and keeps the main code clean
- TRY holds risky code; the matching EXCEPT handles the error; FINALLY always runs (cleanup)
- a subroutine can RAISE an exception for its caller
- handle close to the error or higher up — but never swallow it silently