The traperrors procedure


The traperrors procedure turns automatic error trapping on or off.

If automatic error trapping is on and a trappable error occurs then the program is terminated, and an error message may be printed on the console screen, displayed in a message box, and/or logged to a file, depending on the project setting when the program was compiled.

If automatic error trapping is off and a trappable error occurs then one or more records of type error are created and added to the built-in list variable errors. Each error record describes the error that occured (some in more detail than others). Also the built-in function getlasterror will return a non-zero value to indicate which category of error occured.

If you do not want the program to be terminated when a trappable error occurs, and prefer to handle the error yourself then turn automatic error trapping off (with TrapErrors(false)) before executing code that may cause a trappable error. Then call getlasterror to determine which category of error occured, if any. You will probably want to turn automatic error trapping back on (with TrapErrors(true)) after executing the code that might cause a trappable error.

The (*$I*) compiler directive, also turns automatic error trapping off and on, however new programs should use the traperrors procedure instead. Use of the (*I*) compiler directive continues to be supported for compatibility reasons only.


The traperrors procedure's only parameter is an expression of boolean type that specifies wether automatic error trapping is being turned on or off.


The following simple program asks for the name of a file and
then deterines whether the file exists. It determines whether
the file exists by checking whether the file can be opened for
reading. So technically it is really testing whether the file
file exists AND also if the user has read access to the file.
Anyway the built-in procedure "trapperrors" is used to turn off
error trapping before the program attempts to open the
file (this prevents the normal error trapping procedure from terminating
the program if the file can not be opened). Then the built-in procedure
"getlasterror" is called to determine if an error occured. If an error
occured this program just assumes that the file does not exist.

program DoesFileExist(input, output);
   n : filename;

   function FileExists(name : filename) : boolean;
      f : text;
      reset(f, name);
      FileExists := (getlasterror = 0);
      if FileExists then

   writeln('Enter filename:');
   n := trim(n);
   writeln('Does ''', n, ''' exist?:', FileExists(n))


Operating Systems: All
Standard Pascal: No