typestar

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

  1. Minutes := StrToInt(Raw) raises EConvertError when the text is not an integer.
  2. on E: EConvertError do catches that one class and binds the instance to E.
  3. Report('4o') prints E.Message and the calls after it still run.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Exceptions, step 23 of 27 in Language basics.

← Previous Next →