NAME

docs/user/pir/exceptions.pod - Overview of using exceptions in PIR.

DESCRIPTION

This is a basic overview of how to deal with exceptions from PIR.

EXCEPTIONS

There are two main topics: throwing exceptions and catching exceptions. We'll start with the first.

Throwing exceptions

If you're going to be using exceptions, you probably want to start by including two pasm files that define constants for exception type and severity.

You create exceptions just like you create any other object, with new.

You usually want to at least set a descriptive message about what went wrong.

You also usually want to set a severity and sometimes a type. You can find these in "parrot/include/except_severity.pasm" in runtime.

You actually throw the exception by using the throw op.

Put all together, it looks like this:

Catching exceptions

Parrot maintains a stack of exception handlers. When an exception is thrown, Parrot iterates through the stack looking for a handler that can handle the exception. When it finds a valid exception handler, the exception handler is invoked with the exception as an argument. Exception handlers run in the context of the throw that they're handling.

You create exception handlers just like you create any other object, with new.

You set the target of the exception handler (the code that will be invoked) with the set_attr opcode. Usually this will be a label. You manipulate the exception handler stack with the push_eh and pop_eh opcodes. This is a fairly standard use of exception handlers:

Sometimes you want to be more specific in what you catch. You can set filters on the exception handler based on exception type and severity. The methods you use include .min_severity(), .max_severity(), .handle_types(), and .handle_types_except().

Here's an example of a sub that catches only error exceptions and prints an appropriate log message before exiting.