ZetCode

Error handling and exceptions in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

Pascal reports errors with exceptions: an operation that cannot complete raises an object of a class derived from Exception, and the program either handles it in a try..except block or terminates. The run-time library defines exceptions for arithmetic faults, failed conversions, file errors, and many other conditions, and a program can define its own classes for its own rules. This article follows Pascal objects and classes, because the cleanup examples use objects; it shows how to catch specific exceptions, create and propagate custom ones, release resources with finally, convert strings safely, use assertions, and read the exit status of a crashed program.

try..except

The try block marks the statements that may raise. The except part lists handlers with on E: SomeException do; the first handler whose class matches the raised object runs, and the others are skipped. A handler for Exception catches everything and should come last. When no handler matches, the exception propagates to the caller.

divide.pas
program divide;
{$mode objfpc}{$H+}

uses SysUtils;

var
  A, B: Integer;

begin
  A := 10;
  B := 0;
  try
    WriteLn(A div B);
  except
    on E: EDivByZero do
      WriteLn('integer division: ', E.ClassName, ': ', E.Message);
    on E: EZeroDivide do
      WriteLn('real division: ', E.ClassName, ': ', E.Message);
    on E: Exception do
      WriteLn('other error: ', E.ClassName, ': ', E.Message);
  end;
  WriteLn('program continues');
end.

A div B with B = 0 raises EDivByZero, whose message is Division by zero. The EZeroDivide handler would catch the corresponding real division, but this expression is integer division, so it never matches. After the handler runs, control continues after the end, which is why the last line is printed. An exception leaves the try block immediately: any statements between the raise and the end are skipped.

$ fpc -gl divide.pas
$ ./divide
integer division: EDivByZero: Division by zero
program continues

Custom exceptions

A custom exception is a class derived from Exception. It inherits the Message property and the constructor that sets it, and it can add fields for structured details. Raising it with raise unwinds the call stack until a matching handler is found. A handler can log the error and then use a bare raise to pass the same object to an outer handler.

custom.pas
program custom;
{$mode objfpc}{$H+}

uses SysUtils;

type
  EValidation = class(Exception)
  private
    FField: string;
  public
    constructor Create(const AField, AMessage: string);
    property Field: string read FField;
  end;

constructor EValidation.Create(const AField, AMessage: string);
begin
  inherited Create(AMessage);
  FField := AField;
end;

procedure CheckAge(Age: Integer);
begin
  if Age < 0 then
    raise EValidation.Create('age', 'age cannot be negative');
end;

procedure Validate;
begin
  CheckAge(-5);
  WriteLn('not reached');
end;

begin
  try
    try
      Validate;
    except
      on E: EValidation do
      begin
        WriteLn('logging: ', E.Field, ': ', E.Message);
        raise;
      end;
    end;
  except
    on E: EValidation do
      WriteLn('handled: ', E.Field, ': ', E.Message);
  end;
end.

CheckAge raises the exception three calls deep, inside Validate. The inner handler logs the field and message and re-raises the same object, so the outer handler sees it too. The WriteLn('not reached') never runs. The RTL owns the exception object while it is handled and destroys it automatically after the outermost matching handler finishes, so the program does not free it.

$ fpc -gl custom.pas
$ ./custom
logging: age: age cannot be negative
handled: age: age cannot be negative

try..finally

try..finally guarantees that the finally part runs whether the block completes normally, raises an exception, or leaves through Exit. It is the standard way to release an object, close a file, or unlock a resource. Every object created in the classes article was freed explicitly; wrapping the work in try..finally makes that release unconditional. The exception is not handled by finally: it continues to propagate after the cleanup, so a try..finally is often nested inside a try..except.

cleanup.pas
program cleanup;
{$mode objfpc}{$H+}

uses SysUtils, Classes;

var
  Log: TStringList;

procedure Work;
begin
  Log.Add('step 1');
  raise Exception.Create('failure in Work');
  Log.Add('step 2');
end;

begin
  Log := TStringList.Create;
  try
    try
      Work;
    except
      on E: Exception do
        WriteLn('caught: ', E.Message);
    end;
    WriteLn('log entries: ', Log.Count);
    WriteLn('last: ', Log[Log.Count - 1]);
  finally
    WriteLn('freeing the log');
    Log.Free;
  end;
end.

Work adds one entry and then raises, so the second Add is skipped and the list has one item. The outer finally runs after the exception has been handled and frees the list. Without it, the list would leak. If the exception had not been handled, the finally would still run before the program terminated with an unhandled exception.

$ fpc -gl cleanup.pas
$ ./cleanup
caught: failure in Work
log entries: 1
last: step 1
freeing the log

Conversions and EConvertError

Numeric conversion routines raise EConvertError when the string does not contain a valid number. Catching it lets a program print its own message and continue, while the Try... family of functions avoids the exception entirely by returning a Boolean. The two styles are equivalent for validation; the Try form is faster when invalid input is common and is easier to use in a loop.

convert.pas
program convert;
{$mode objfpc}{$H+}

uses SysUtils;

var
  S: string;
  N: Integer;

begin
  S := '42x';
  try
    N := StrToInt(S);
    WriteLn('value: ', N);
  except
    on E: EConvertError do
      WriteLn('cannot convert: ', E.Message);
  end;

  if TryStrToInt(S, N) then
    WriteLn('TryStrToInt value: ', N)
  else
    WriteLn('TryStrToInt failed');

  if TryStrToInt(' 42 ', N) then
    WriteLn('spaces accepted: ', N)
  else
    WriteLn('spaces rejected');
end.

StrToInt('42x') raises because of the trailing letter, and the message quotes the offending string. TryStrToInt returns False for the same input, so neither branch raises. The last test shows that leading and trailing spaces are not accepted by TryStrToInt; a program reading user input should call Trim first. TryStrToFloat follows the same pattern for real numbers.

$ fpc -gl convert.pas
$ ./convert
cannot convert: "42x" is an invalid integer
TryStrToInt failed
spaces rejected

Assertions

Assert(Condition, Message) states an invariant that should always hold. Assertions are compiled out by default: the condition and the message are not evaluated, and the program continues even when the condition is false. The -Sa compiler switch or the {$ASSERTIONS ON} directive enables them. A failed assertion prints the message together with the file and line, then exits with status 227.

check.pas
program check;
{$mode objfpc}{$H+}

var
  X: Integer;

begin
  X := 5;
  Assert(X > 10, 'X must be greater than 10');
  WriteLn('not reached');
end.

With -Sa the condition is false, so the program prints the message and stops before the WriteLn. Without the switch the assertion disappears at compile time and the program prints not reached and exits with 0. Assertions document preconditions and catch programmer errors during testing; they should not replace input validation, because user input can violate them in a release build where they are disabled.

$ fpc -gl -Sa check.pas
$ ./check
X must be greater than 10 (check.pas, line 7).

$ echo $?
227
$ fpc -gl check.pas
$ ./check
not reached
$ echo $?
0

Unhandled exceptions

An exception that reaches the main block without a handler terminates the program. The RTL prints An unhandled exception occurred together with the exception class, the message, and a short backtrace that includes the source line when the program was compiled with -gl. The process exit status is 217, which a shell can test like any other failure.

unhandled.pas
program unhandled;
{$mode objfpc}{$H+}

uses SysUtils;

begin
  WriteLn('before');
  raise Exception.Create('something went wrong');
  WriteLn('after');
end.

The first line is printed, the raise skips the rest of the block, and the RTL prints the report. The address in the backtrace depends on the compiler version, the optimization level, and the linked units, so it is not a stable part of the output. A program that wants a friendly message instead of the report wraps its main work in try..except and prints E.Message, returning a non-zero exit code.

$ fpc -gl unhandled.pas
$ ./unhandled
before
An unhandled exception occurred at $00000000004010D3:
Exception: something went wrong
  $00000000004010D3  main,  line 5 of unhandled.pas

$ echo $?
217

Next steps

Exceptions interact with memory management, which the memory management article covers, and with file access, where {$I-} and IOResult provide a non-exception path. The command-line arguments article shows a parser that halts with a usage code, and the procedural types article explains the callbacks whose exceptions propagate through these handlers.

Source

Free Pascal Reference guide: exception handling

Free Pascal: Exception

Free Pascal: Assert

In this article we caught specific and general exceptions, built a custom exception with extra data, re-raised it through a handler, cleaned up with finally, converted strings with and without exceptions, enabled assertions, and read the status of an unhandled error. The series continues with inheritance and polymorphism; the memory management article later shows the heap that finally protects.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.