Parrot Virtual Machine/Exception Handling

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Exceptions[edit | edit source]

Exceptions are errors that are caused in a program. However, unlike an ordinary error which causes the program to terminate unexpectedly, exceptions are controlled and can be recovered from without having to restart the program.

In Parrot, exceptions are objects. This means you create an exception using the new keyword, and manipulate an exception using methods on that object. Before we discuss exceptions any further, we need to discuss some terminology. Readers who are familiar with exceptions in other programming languages can probably skip these definitions.

To throw an exception means to create an exception object. Once an exception has been created, the system enters a kind of "panic state" where it attempts to fix the exception. If the exception cannot be fixed, the program terminates.
To raise an exception is the same as to throw one.
A handler is a routine which can fix an exception. When an exception is raised and the system enters panic mode, it looks for a handler. If there is a handler available, the exception is sent to that handler. If no handlers are available to handle the exception, the system will terminate.
A handler that receives an exception object is said to "catch" it. Whenever an exception is thrown, a handler should be available to catch it. Again, if no handlers are available to catch an exception, Parrot will exit.
All handlers are not equipped to handle all exceptions. If a handler catches an exception that it cannot fix, it can optionally rethrow that exception. Rethrowing causes the system to search for a different handler.

Creating an Exception[edit | edit source]

Creating a new exception object in PIR is deceptively simple:

$P0 = new 'Exception'

Exceptions are hash-like, which means they have named fields. One such field is the '_message' field, which contains the name of the exception. Exception handlers will check the name to determine if they can handle a particular exception, or if it needs to be rethrown.

Creating a Handler[edit | edit source]

In Parrot, a handler is a label that the system jumps to in the event of an exception. These labels are stored in a stack structure. The exception handler on the top receives the instruction, but if it rethrows, the exception will be propagated down through the exception stack until it is finally handled.

Resources[edit | edit source]

Previous Parrot Virtual Machine Next
Multithreading_and_Concurrency Classes and Objects