Exceptions and Exception Handlers
Exceptions provide a way of calling a piece of code outside the normal flow of control. They are mainly used for error reporting or cleanup tasks, but sometimes exceptions are just a funny way to branch from one code location to another one. The design and implementation of exceptions in Parrot isn’t complete yet, but this section will give you an idea where we’re headed.
Exceptions are objects that hold all the information needed to handle the exception: the error message, the severity and type of the error, etc. The class of an exception object indicates the kind of exception it is.
Exception handlers are derived from continuations. They are ordinary
subroutines that follow the Parrot-calling conventions, but are never
explicitly called from within user code. User code pushes an
exception handler onto the control stack with the
set_eh opcode. The system calls the installed
exception handler only when an exception is thrown (perhaps because
of code that does division by zero or attempts to retrieve a global
that wasn’t stored.)
newsub P20, .Exception_Handler, _handler set_eh P20 # push handler on control stack null P10 # set register to null find_global P10, "none" # may throw exception clear_eh # pop the handler off the stack . . . _handler: # if not, execution continues here is_null P10, not_found # test P10 . . .
This example creates a new exception handler subroutine with the
newsub opcode and installs it on the control stack
with the set_eh ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access