When a program crashes because of a run time error (such as dividing by zero), you do not normally get a chance to respond to the error in any way. An exit procedure allows you to "clean up" in the event of an error, although you cannot easily resume the program.
One possible use for an exit procedure is to close an output file: if a file is not closed, then data can be lost. A graphics program might want to change back to text mode if it crashes, so that the user isn't left with a messed up screen. The most common use that I've found in olympiad problems is in optimisation problems where partial marks can be obtained for a non-optimal solution: keep track of the best solution found so far, and if the program crashes then quickly output this solution. This could also be done by just writing solutions as they are found, overwriting previous solutions, but this has two disadvantages:
The variable exitproc
contains a pointer to the default exit
procedure. You must set it to point to your own exit procedure. However, you
must save the original pointer and restore it inside your exit procedure to
allow the normal shutdown procedure to take place.
var oldexitproc : pointer; {the default exit procedure} procedure myexitproc; begin exitproc := oldexitproc; writeln('myexitproc reached with exitcode ', exitcode); exitcode := 0; end; begin oldexitproc := exitproc; exitproc := @myexitproc; { do stuff } end.
The error is suppressed by setting exitcode
to
0
.
If you test this in a program that crashes, you may notice that Free
Pascal still produces the usual error log that indicates an error
(although the operating system still thinks the program worked). If you
want to suppress this as well, then set the variable
erroraddr
to nil
.
The exit procedure is run whether your program crashes or terminates normally, so it is a great place to put the code for writing your output file to ensure that it definitely gets written.
Last updated Sun Nov 28 22:04:38.0000000000 2004. Copyright Bruce Merry (bmerry '@' gmail dot. com).