Grade 12 expects programs that survive bad input and that persist data between runs.
try…except catches a runtime error so the program can recover. try…finally is different: it catches nothing, but guarantees the cleanup runs — which is how you make sure files get closed and objects get freed.
Example
uses SysUtils; try WriteLn(a div b); except on E: EDivByZero do WriteLn('Cannot divide by zero'); on E: Exception do WriteLn('Something went wrong: ', E.Message); end;
| Exception | Raised by |
|---|---|
| EDivByZero | Integer division by zero |
| EConvertError | StrToInt on text that isn't a number |
| ERangeError | Array index outside its declared bounds |
| EInOutError | File operations — missing file, wrong mode |
Text files use the same four-step pattern every time: assign, open, work, close.
Example
var f: TextFile; line: String; begin AssignFile(f, 'data.txt'); Reset(f); // Rewrite to create/overwrite, Append to add try while not Eof(f) do begin ReadLn(f, line); WriteLn(line); end; finally CloseFile(f); // runs even if something above fails end; end.
💡 Exam Tip
StrToIntDef(s, -1) avoids needing a try block at all for input conversion, and memos accept it — reach for it before writing exception handling you don't need.