Errors in Pascal

program ErrorHandling;

uses
  SysUtils;

type
  ECustomError = class(Exception);

var
  ErrOutOfTea: ECustomError;
  ErrPower: ECustomError;

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

procedure MakeTea(arg: Integer);
begin
  if arg = 2 then
    raise ErrOutOfTea
  else if arg = 4 then
    raise ECustomError.CreateFmt('making tea: %s', [ErrPower.Message]);
end;

begin
  ErrOutOfTea := ECustomError.Create('no more tea available');
  ErrPower := ECustomError.Create('can''t boil water');

  for var i in [7, 42] do
  begin
    try
      var r := F(i);
      WriteLn('f worked: ', r);
    except
      on E: ECustomError do
        WriteLn('f failed: ', E.Message);
    end;
  end;

  for var i := 0 to 4 do
  begin
    try
      MakeTea(i);
      WriteLn('Tea is ready!');
    except
      on E: ECustomError do
      begin
        if E = ErrOutOfTea then
          WriteLn('We should buy new tea!')
        else if (E.Message.Contains(ErrPower.Message)) then
          WriteLn('Now it is dark.')
        else
          WriteLn('unknown error: ', E.Message);
      end;
    end;
  end;
end.

In Pascal, error handling is typically done using exceptions. Here’s an explanation of the key differences and adaptations:

  1. Instead of returning errors, we raise exceptions in Pascal.

  2. We define a custom exception type ECustomError that inherits from the built-in Exception class.

  3. The F function now raises an exception instead of returning an error.

  4. We create global exception instances ErrOutOfTea and ErrPower to serve as sentinel errors.

  5. The MakeTea procedure raises exceptions instead of returning errors.

  6. In the main program, we use try-except blocks to handle exceptions.

  7. To check for specific errors, we compare the caught exception with our sentinel errors or check the error message.

  8. Pascal doesn’t have a direct equivalent to Go’s errors.Is function. Instead, we compare exception instances directly or check the error message content.

When you run this program, it will produce output similar to the Go version, demonstrating error handling in Pascal:

f worked: 10
f failed: can't work with 42
Tea is ready!
Tea is ready!
We should buy new tea!
Tea is ready!
Now it is dark.

This example shows how to implement error handling in Pascal using exceptions, which is the idiomatic way to handle errors in this language.