Theory Notes/💻 Topic 1: Solution Development/12.1.1
12.1.1Grade 12

Application Development: Error Handling & Text Files

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;

ExceptionRaised by
EDivByZeroInteger division by zero
EConvertErrorStrToInt on text that isn't a number
ERangeErrorArray index outside its declared bounds
EInOutErrorFile 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.