Home
CBM
  ASCII-X
  BASIC
    Disk Commands
    Enter RUN mode
    Program Format
    Secret Variables
    Variable Format
    Expressions
    Keywords
      (divide)
      (equal)
      (less)
      (minus)
      (more)
      (multiply)
      (plus)
      (power)
      Abs
      And
      Append
      Asc
      Atn
      Auto
      Backup
      Bank
      Begin
      Bend
      Bload
      Boot
      Box
      Bsave
      Bump
      Catalog
      Char
      Chr
      Circle
      Close
      Clr
      Cmd
      Collect
      Collision
      Color
      Concat
      Cont
      Copy
      Cos
      Data
      Dclear
      Dclose
      Dec
      Def
      Delete
      Dim
      Directory
      Dispose
      Dload
      Do
      Dopen
      Draw
      Ds
      Ds string
      Dsave
      Dverify
      El
      Else
      End
      Envelope
      Er
      Err
      Exit
      Exp
      Fast
      Fetch
      Filter
      Fn
      For
      Fre
      Get
      Get num
      Getkey
      Go
      Gosub
      Goto
      Graphic
      Gshape
      Header
      Help
      Hex
      If
      Input
      Input num
      Instr
      Int
      Joy
      Key
      Left
      Len
      Let
      List
      Load
      Locate
      Log
      Loop
      Mid
      Monitor
      Movspr
      New
      Next
      Not
      Off
      On
      Open
      Or
      Paint
      Peek
      Pen
      Pi
      Play
      Pointer
      Poke
      Pos
      Pot
      Print
      Print num
      Pudef
      Quit
      Rclr
      Rdot
      Read
      Record
      Rem
      Rename
      Renumber
      Restore
      Resume
      Return
      Rgr
      Right
      Rlum
      Rnd
      Rreg
      Rspcolor
      Rsppos
      Rsprite
      Run
      Rwindow
      Save
      Scale
      Scnclr
      Scratch
      Sgn
      Sin
      Sleep
      Slow
      Sound
      Spc
      Sprcolor
      Sprdef
      Sprite
      Sprsav
      Sqr
      Sshape
      St
      Stash
      Step
      Stop
      Str
      Swap
      Sys
      Tab
      Tan
      Tempo
      Then
      Ti
      Ti string
      To
      Trap
      Troff
      Tron
      Until
      Using
      Usr
      Val
      Verify
      Vol
      Wait
      While
      Width
      Window
      Xor
    Syntax
    Tokens
  C128
  D64plus
  Disk
  Escape Codes
  Hardware
  PCxface
  PETSCII
  Pet2asc
Futurama
IBM PC-AT
Contact
Games
Glossary
Hall of fame
Hall of shame
Miscellaneous
Privacy policy
Programming
Twisty puzzles
KeywordAbbreviationToken (hex)Version(s)Classification
TRAPT{Shift+R}D73.5, 7.0Statement
CATALOGC{Shift+A} D7 4.x Command and Statement 
TRAPT{Shift+R}E24.xStatement
CIRCLEC{Shift+I} E2 3.5, 7.0 Command and Statement 

 
Syntax 
TRAP lineNumber ]
 
ParametersTypeLegal Value(s)Default ValueNote(s)
lineNumberUnsigned Integer0 ~ 63999If used, the program line must exist.
 
 
 
Purpose 
Program error control; set (or forget) a subroutine to be called when an error occurs in a program.

 
 
Remarks 
TRAP without a lineNumber disables error trapping in the current program (this is also done by CLR).  If lineNumber is given, it is saved as a Secret Variable ("Trap Line") and enables a special subroutine, called an error trap (described below), that is called when an error occurs in a program.
 
Unlike GOSUB and GOTO, the lineNumber does not need to be a literal value; it can be any numeric expression.  However, using a non-literal value will usually cause a silent error with RENUMBER which only updates line numbers written as a literal number.
 
If the lineNumber is given, it must exist or an UNDEF'D STATMENT ERROR occurs as soon as TRAP is executed (not later when another error occurs).  If lineNumber is not numeric, a TYPE MISMATCH ERROR occurs.  If a numeric expression is used but is not valid, SYNTAX ERROR occurs as soon as TRAP is executed.  If the lineNumber is not a legal value, an ILLEGAL QUANTITY ERROR is generated as soon as TRAP is executed.
 
Attempting to use TRAP in direct mode generates ILLEGAL DIRECT ERROR.  An error that occurs in direct mode never calls a trap routine.
 
Now lets assume an error trap has been successfully set.  If an error occurs later in the program, the reserved variables EL, ER, and ERR$ will be set (along with another secret variable "Trap Address"), error trapping will temporarily be disabled, and BASIC will effectively do a GOSUB to the lineNumber specified in the most recent TRAP statement (secret variable, "Trap Line").  There are two main differences from a normal GOSUB.  First the 'return' location is initially set to the statment that caused the error (and not the following statement, as with GOSUB).  Second, the special RESUME keyword should be used to exit the error trap routine (instead of RETURN used with GOSUB); the reason for this is so error trapping can be re-enabled after the current error has been handled.
 
This method means an error that occurs in the trap routine will halt the program and return to direct mode.  This is mainly because (without some new hypothetical keywords) BASIC would get stuck in an infinite loop if an error occured in the trap routine.  In other words, nested error traps (sometimes called a double-fault) are not directly possible to handle.  (It might be possible with some tricks.)
 
Although probably not useful in a finished program, you can use the HELP keyword in a trap routine to show, on the text screen, the statement in a program line where the error occured.  This is the statement that will be re-executed by RESUME (without any arguments); RESUME NEXT would continue execution at the first colon (:) past the highlighted error (or the next line if none).  BASIC only gives you the line number (EL) and not the exact position of the error (stored in secret variable "Trap Address"), so the use of HELP can be quite valuable.
 
Although an error can't be (effectively) trapped while in a trap routine, the TRAP keyword may be used.  For example, to set a new trap routine or disable error trapping in the future.  This will not affect how RESUME works, unless an error occurs before RESUME is executed.  In this case, the new TRAP line would be called (assuming a new routine was set, as opposed to completely disabling error traps).  Assuming the new trap routine RESUME'd this current error trap routine, then this error trap routine would generate a CAN'T RESUME ERROR (or in some versions, UNABLE TO RESUME ERROR) when the current trap routine later executes RESUME (assuming of course this error trap routine does execute RESUME)... if that were to happen, the newly-set TRAP routine would be called again... this might result in an infinite loop, depending on how the newly-set error trap routine is written.
 
Sorry if that last paragraph if confusing.  The short version is so-called "double-faults" are often "fatal" because they will halt the program despite TRAP or result in an infinite loop (or other strange behavior).
 
Note that like GOSUB, calling the trap routine requires 5 bytes of the BASIC stack; an OUT OF MEMORY ERROR occurs if this is not available.
 
The error trap routine (that a BASIC programmer writes) will normally examine the variables EL and ER and decide upon some action to take (based on the type and location of the error).  The action may include setting some variables which are needed in the current (or soon-to-occur) statment so they will work properly.  A good example would be DIVISON BY ZERO error, where the trap routine might want to set some default value (like plus or minus 90 degrees).
 
The error trap should end with RESUME.  This pops the entry from the BASIC stack that was pushed when the error occured and re-enables error trapping for any future error.
 
Note that some errors will not invoke your trap routine!  For some errors with INPUT, BASIC will do its normal thing.  For some I/O errors (which really need error trapping) the computer will exit to immediate mode and print an error message... gee thanks for nothing!  Also be sure to the page on ERR$ which lists the errorNumbers and associated string message because the errorNumbers (the ER value) vary between different versions of BASIC.
 
Example:
NEW

READY.
10 TRAP 100
20 INPUT "RECTANGULAR X,Y"; X,Y
30 PRINT "POLAR M,A";
40 PRINT SQR(X*X + Y*Y) ",";
50 A = 180/π * ATN(Y/X)
60 PRINT A : PRINT
70 GOTO 20
100 IF EL <> 50 THEN PRINT "UNEXPECTED" : STOP
110 A = 90*SGN(Y)
120 RESUME NEXT
RUN
RECTANGULAR X,Y? CAT (user input)
?REDO FROM START                 note BASIC did not call trap routine
RECTANGULAR X,Y? 5 (user input)
?? 5 (user input)                note BASIC did not call trap routine
POLAR M,A 7.07106781, 45
RECTANGULAR X,Y? 3,4 (user input)
POLAR M,A 5, 53.1301024          note there was no error
RECTANGULAR X,Y? 0,4 (user input)
POLAR M,A 4, 90                  note BASIC called the trap routine (not obvious)
 
 
 
Compare With 
 
 
Contrast With 
 
See Also 

© H2Obsession, 2014