Exception handling
| English | Chinese | Pinyin |
|---|---|---|
| exception | 异常 | yì cháng |
| exception handling | 异常处理 | yì cháng chǔ lǐ |
| raise | 抛出 | pāo chū |
When things go wrong
- 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.

TRY runs the code; on an error EXCEPT handles it; FINALLY always runs
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).
How exception handling flows
Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing.
Match each exception-handling keyword to its job.
TRY guards the risky code, EXCEPT catches, FINALLY cleans up either way, RAISE throws an error to be caught.
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.
A subroutine uses RAISE to:
RAISE throws an exception up to the caller, which can catch it with EXCEPT.
Silently "swallowing" an exception (catching it but doing nothing) hides real errors and makes debugging hard — you should handle it or at least log it.
An empty handler hides the very problems you need to find; always respond or record the error.
You've got it
- 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