try-except in Delphi
Three strings through StrToInt, one of them not a number, handled instead of crashing.
program TryExcept;
uses SysUtils;
procedure Report(const Raw: string);
var Minutes: Integer;
begin
try
Minutes := StrToInt(Raw); // raises EConvertError on junk input
WriteLn(Format('%-6s %3d min', [Raw, Minutes]));
except
on E: EConvertError do // on-do names the class and the instance
WriteLn(Format('%-6s skipped: %s', [Raw, E.Message]));
end;
end;
begin
Report('45');
Report('4o'); // the handler runs, then the program carries on
Report('12');
end.
How it works
Minutes := StrToInt(Raw)raisesEConvertErrorwhen the text is not an integer.on E: EConvertError docatches that one class and binds the instance toE.Report('4o')printsE.Messageand the calls after it still run.
Keywords and builtins used here
FormatIntegerReportStrToIntWriteLnbeginconstdoendexceptonprocedureprogramstringtryusesvar
The run, in numbers
- Lines
- 18
- Characters to type
- 460
- Tokens
- 97
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in Exceptions, step 23 of 27 in Language basics.