In order to issue an error which BASIC can process properly you must do the following:

  1. Load the A register with the appropriate error number. If this is an error which exists in other versions of BBC BASIC, you should use the same number (e.g. "Escape" is error 17). If you need to allocate numbers for your own errors, please use only values greater than 127. If the error number is zero the error is "fatal", i.e. untrappable by the user with ON ERROR. You should use this with "catastrophic" errors from which the user cannot hope to recover.
  2. Call the routine EXTERR, accessible via the address &4080. Despite the fact that it is CALLed this routine never returns to the caller. A CALL is used simply to pass the address of the error string which follows.
  3. Place the required error string immediately following the CALL EXTERR, terminated with a NUL character (ASCII 00). BASIC will store a pointer to this string, used if REPORT is subsequently issued, so you should not subsequently overwrite the string if it is in RAM.

For example, to issue the "Escape" error from your code:

LD A,17             ; Code for "Escape"
CALL EXTERR         ; Tell BASIC to process error
DEFM "Escape"+CHR$0 ; Error string terminated by NUL

If you prefer the error string to be elsewhere, the equivalent can be achieved as follows:

LD A,17      ; Code for "Escape"
LD HL,ERRMES ; Pointer to error string
PUSH HL      ; Put address on stack
JP EXTERR    ; Tell BASIC to process error

BASIC resets its stack pointer (to the current value of HIMEM) when an error

occurs so there is no need to ensure that SP has any particular value when EXTERR is called, except (of course) that it must point to a location where the address of the error string can be PUSHed without doing any damage.