NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 20 of 30 · Files and errorsHandle an error

try ... except catches an error, try ... finally always runs the last part.

Programming on the NAS › Pascal in 30 lessons

20-exceptions.pas Download 20-exceptions.pas

program Exceptions;
{$mode objfpc}{$H+}
uses
  SysUtils, Classes;
var
  Lines: TStringList;
begin
  Lines := TStringList.Create;
  try
    try
      Lines.LoadFromFile(ParamStr(1));
      WriteLn(ParamStr(1), ' has ', Lines.Count, ' lines');
    except
      on E: Exception do
      begin
        WriteLn(E.Message);
        ExitCode := 1;
      end;
    end;
  finally
    Lines.Free;
  end;
end.

Terminal

$ ./20-exceptions words.txt
words.txt has 3 lines
$ ./20-exceptions missing.txt; echo "exit code $?"
Unable to open file "missing.txt": No such file or directory
exit code 1

Exercise

Try a second file when the first one is missing.