4.10.3.2 Throwing exceptions from applications and libraries
User predicates are free to choose the structure of their exception terms (i.e., they can define their own conventions) but should adhere to the ISO standard if possible, in particular for libraries.
Notably, exceptions of the shape error(Formal,Context)
are recognised by the development tools and therefore expressing
unexpected situations using these exceptions improves the debugging
experience.
In SWI-Prolog, the second argument of the exception term, i.e., the
Context argument, is generally of the form
context(Location, Message)
, where:
- Location
describes the execution context in which the exception occurred. While the Location argument may be specified as a predicate indicator (Name/Arity), it is typically filled by thelibrary(prolog_stack)
library. This library recognises uncaught errors or errors caught by catch_with_backtrace/3 and fills the Location argument with a backtrace. - Message
provides an additional description of the error or can be left as a fresh variable if there is nothing appropriate to fill in.
ISO standard exceptions can be thrown via the predicates exported
from library(error)
. Termwise, these predicates look
exactly like the
Formal of the ISO standard error term they throw:
- instantiation_error/1 (the argument is not used: ISO specifies no argument)
- uninstantiation_error/1
- type_error/2
- domain_error/2
- existence_error/2
- existence_error/3 (a SWI-Prolog extension that is not ISO)
- permission_error/3
- representation_error/1
- resource_error/1
- syntax_error/1