Exit in Pascal

Here’s an idiomatic Pascal example demonstrating the concept of program exit:

program ExitDemo;

uses
  SysUtils;

procedure CleanupProcedure;
begin
  WriteLn('Cleanup procedure executed.');
end;

begin
  try
    WriteLn('Program started.');
    
    // Register a cleanup procedure
    AddExitProc(@CleanupProcedure);
    
    // Exit the program with status code 3
    Halt(3);
    
    // This line will never be executed
    WriteLn('This will not be printed.');
  except
    on E: Exception do
      WriteLn('An error occurred: ', E.Message);
  end;
end.

This Pascal program demonstrates how to exit a program with a specific status code. Here’s an explanation of the code:

  1. We define a CleanupProcedure that will be called when the program exits normally.

  2. In the main program block:

    • We use AddExitProc to register our cleanup procedure.
    • We call Halt(3) to immediately terminate the program with exit code 3.
    • Any code after Halt will not be executed.
  3. We wrap the main code in a try-except block to handle any unexpected exceptions.

To compile and run this program:

  1. Save the code in a file named ExitDemo.pas.

  2. Use a Pascal compiler (like Free Pascal) to compile the program:

    $ fpc ExitDemo.pas
  3. Run the compiled program:

    $ ./ExitDemo
    Program started.
  4. Check the exit status:

    $ echo $?
    3

Note that the cleanup procedure is not executed when using Halt. If you want to ensure cleanup code runs, you should use the try-finally construct instead of relying on exit procedures.

This example showcases Pascal’s approach to program termination and exit codes, which differs from some other languages. In Pascal, you explicitly call Halt to exit with a specific status, rather than returning a value from the main function.