Exit in Pascal
Here’s an idiomatic Pascal example demonstrating the concept of program exit:
This Pascal program demonstrates how to exit a program with a specific status code. Here’s an explanation of the code:
We define a
CleanupProcedure
that will be called when the program exits normally.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.
- We use
We wrap the main code in a try-except block to handle any unexpected exceptions.
To compile and run this program:
Save the code in a file named
ExitDemo.pas
.Use a Pascal compiler (like Free Pascal) to compile the program:
Run the compiled program:
Check the exit status:
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.