postscriptError Handling


Syntax

  • { -code- } stopped { -error- }{ -no-error- } ifelse % error catching frame

  • $error /errorname get % stackunderflow typecheck rangecheck etc
    $error /newerror get % bool. put false to deactivate error
    $error /ostack get % copy of operand stack at point of error

  • errordict /stackoverflow { -additional-code- /stackoverflow signalerror} put
    % execute additional code on types of errors (here, the /stackoverflow error).

Remarks

There are two levels to error handling in postscript. This dichotomy applies both to the way the interpreter handles errors as well as the means available to the user (programmer) to control the handling.

The lower level is an unusual control structure stop ... stopped. stopped behaves much like a looping construct in that it establishes a mark on the execution stack that can be jumped-to if the exit operator (for a loop) or stop operator (for a stopped-context) is called. Unlike a looping construct, stopped yields a Boolean on the stack indicating whether stop was called (otherwise the procedure passed to stopped is known to have executed to completion.

When a PostScript error occurs, like stackunderflow maybe, the interpreter looks up the error's name in errordict which lives in systemdict. If the user has not replaced the procedure in errordict, then the default error procedure will take snapshots of all the stack and place them in $error, another dictionary in systemdict. Finally, the default procedure will call stop which pops the user program from the exec stack and executes the interpreter's error printing procedure called handleerror in errordict.

So using all of this knowledge, you can catch errors by wrapping a section of code in { ... } stopped. You can rethrow an error by calling stop. You can determine what type of error occurred with $error /errorname get.

You can also change the default behavior for a specific type of error by replacing the procedure with that name in errordict. Or change the format of printing the error report by replacing /handleerror in errordict.