Chapter 6

Exceptions

On this page

An exception is an event that occurs during the execution of a program. An exception requires special treatment. In Picat, an exception is just a term. A built-in exception is an atom or a structure. If it is a structure, the name denotes the type of the exception, and the arguments provide other information about the exception, such as the source, which is the goal or function that raised the exception.

6.1 Built-in Exceptions

Picat throws many types of exceptions. The following are some of the built-in exceptions:1

6.2 Throwing Exceptions

The built-in predicate throw(Exception) throws Exception. After an exception is thrown, the system searches for a handler for the exception. If none is found, then the system displays the exception and aborts the execution of the current query. It also prints the backtrace of the stack if it is in debug mode. For example, for the function call open("abc.txt"), the following message will be displayed if there is no file that is named "abc.txt".

    *** error(existence_error(source_sink, abc.txt), open)

6.3 Defining Exception Handlers

All exceptions, including those raised by built-ins and interruptions, can be caught by catchers. A catcher is a call in the form:

      catch(Goal, Exception, Handler)

which is equivalent to Goal, except when an exception is raised during the execution of Goal that unifies with Exception. When such an exception is raised, all of the bindings that have been performed on variables in Goal will be undone, and Handler will be executed to handle the exception. Note that Exception is unified with a renamed copy of the exception before Handler is executed. Also note that only exceptions that are raised by a descendant call of Goal can be caught.

The call call_cleanup(Call, Cleanup) is equivalent to call(Call), except that Cleanup is called when Call succeeds deterministically (i.e., with no remaining choice point), when Call fails, or when Call raises an exception.

1In the current implementation, exceptions thrown by B-Prolog are not compliant with the documentation.