{--------------------------------------------------------------}
{                          Trapper                             }
{                                                              }
{     Demonstration of Turbo Pascal runtime error trapping     }
{                                                              }
{                             by Jeff Duntemann                }
{                             Turbo Pascal V3.0                }
{                             Last update 3/4/86               }
{                                                              }
{    From the book, COMPLETE TURBO PASCAL, by Jeff Duntemann   }
{    Scott, Foresman & Co. (c) 1986,1987  ISBN 0-673-18600-8   }
{--------------------------------------------------------------}

PROGRAM Trapper;

VAR
  R : Real;


PROCEDURE RuntimeErrorTrap(ErrorData, ErrorAddress : Integer);

VAR
  ErrorType,ErrorNumber : Byte;

BEGIN
  ErrorType   := Hi(ErrorData);
  ErrorNumber := Lo(ErrorData);
  CASE ErrorType OF
    0 : BEGIN                   { User-issued program break }
          Write('You typed Control-C to interrupt--');
          Writeln('returning to the operating system...');
          Halt(1)                          { Remove parm for Z80! }
        END;

    1 : CASE ErrorNumber OF     { I/O error }
          4 : Writeln('Block I/O attempted on closed file!');
              { Add other appropriate action statements here }
        END; { CASE }

    2 : CASE ErrorNumber OF     { Runtime error }
          1 : Writeln('Floating point overflow!');
          2 : Writeln('Divide by zero error!');
          3 : Writeln('Square root of negative value error!');
          4 : Writeln('Natural log argument zero or negative!');
          255 : Writeln('Heap/stack collision!');
        END; { CASE }

   END; { CASE }
   Halt(ErrorNumber + (ErrorType-1)*32)    { Remove parm for Z80! }
END;


BEGIN
  ClrScr;
  ErrorPtr := Ofs(RuntimeErrorTrap);       { 8086 error trap set }
  {ErrorPtr := Addr(RuntimeErrorTrap);}    { Z80 error trap set }
  Readln;
  R := 42.0 / 0.0;     { Try to divide by zero to awaken trap }
END.
