Custom Errors in Pascal

Our first program demonstrates how to create and use custom errors. Here’s the full source code:

program CustomErrors;

uses
  SysUtils;

type
  TArgError = class(Exception)
  private
    FArg: Integer;
  public
    constructor Create(AArg: Integer; const AMessage: string);
    property Arg: Integer read FArg;
  end;

constructor TArgError.Create(AArg: Integer; const AMessage: string);
begin
  inherited Create(AMessage);
  FArg := AArg;
end;

function F(Arg: Integer): Integer;
begin
  if Arg = 42 then
    raise TArgError.Create(Arg, 'can''t work with it')
  else
    Result := Arg + 3;
end;

var
  Result: Integer;
  E: Exception;

begin
  try
    Result := F(42);
  except
    on E: TArgError do
    begin
      WriteLn(E.Arg);
      WriteLn(E.Message);
    end;
    on E: Exception do
      WriteLn('Error doesn''t match TArgError');
  end;
end.

In this example, we define a custom error type TArgError that inherits from the standard Exception class. It includes an additional Arg property to store the problematic argument.

The F function demonstrates how to raise our custom error when a specific condition is met (in this case, when the argument is 42).

In the main program, we use a try-except block to handle the error. We specifically catch TArgError to demonstrate how to access its custom properties.

To run the program, save it as CustomErrors.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc CustomErrors.pas
$ ./CustomErrors
42
can't work with it

This example shows how to create and use custom error types in Pascal, allowing for more detailed error handling in your programs.