define-exception defines an exception type whose values can be signaled with throw and caught with catch or handle.
Syntax
;; Coalton-defined exception algebraic data type
(define-exception ⟨name⟩
⟨docstring⟩?
⟨constructor-spec⟩*)
;; Existing Common Lisp condition type
(repr :native ⟨lisp-condition-type⟩)
(define-exception ⟨name⟩
⟨docstring⟩?)
;; ⟨constructor-spec⟩ := ⟨ctor-name⟩ ⟨docstring⟩?
;; | (⟨ctor-name⟩ ⟨field-type⟩*) ⟨docstring⟩?
Semantics
define-exceptionis a top-level definition form valid insidecoalton-toplevel.- Its constructor syntax matches
define-type, including optional docstrings on the exception type and after each constructor. - Exception types cannot be parameterized by type variables.
- Exception constructors are ordinary Coalton constructors: they can be called to construct exception values, stored in data structures, or passed to functions before being passed to
throw. - Every exception type automatically receives an instance of the marker class
Exception(required bythrow) andRuntimeRepr. Manual instances ofExceptioncannot be written, and an exception type cannot be redefined as a non-exception type. - Native Lisp conditions: With
(repr :native ⟨lisp-condition-type⟩):⟨name⟩wraps an existing Common Lisp condition type rather than defining new constructors (⟨constructor-spec⟩*must be empty).⟨lisp-condition-type⟩must be known at compile time and must be a subtype ofcl:serious-condition. (If defined viacl:define-conditionin the same file, wrap thecl:define-conditionin(eval-when (:compile-toplevel :load-toplevel :execute) ...).)- Native exception values are caught with
((the ⟨name⟩ var) ...)incatchorhandle(which also matches any Common Lisp subtype of⟨lisp-condition-type⟩) or constructed vialisp.
define-exceptiondoes not acceptderiveor anyreprmode other than:native.
Examples
(coalton-toplevel
;; Exception sum type with multiple constructors
(define-exception HttpError
"Errors raised while handling HTTP requests."
(NotFound String)
(Unauthorized String)
Timeout)
;; Bind an existing Common Lisp condition type
(repr :native cl:division-by-zero)
(define-exception DivisionByZero
"Common Lisp's DIVISION-BY-ZERO condition.")
(declare safe-recip (Integer -> (Optional Fraction)))
(define (safe-recip n)
(catch (Some (/ 1 (fromInt n)))
((the DivisionByZero _) None))))
Other notes
- Coalton-defined exception types compile to Common Lisp condition types inheriting from
cl:error, with a distinct condition subclass for each constructor. - The
coalton/exceptionstandard library package predefines native exception types for standard Common Lisp conditions (includingLispErrorforcl:errorandPanicfor Coalton panics). - See
throw,catch, andhandle.