throw signals an exception value, transferring control to the nearest matching catch or handle branch.
Syntax
(throw ⟨exception-expr⟩)
Semantics
⟨exception-expr⟩must have a type:ethat is an instance of theExceptiontype class (which holds exclusively for types defined withdefine-exception).throwhas the polymorphic behaviorException :e => :e -> :a(and unifies with any expected return type, includingVoidor multiple values, because it never returns normally).- Evaluating
(throw ⟨exception-expr⟩)evaluates⟨exception-expr⟩and signals the resulting condition, searching dynamically enclosingcatchandhandleforms from innermost to outermost. - If no enclosing handler matches the thrown exception, the unhandled condition reaches the host Common Lisp condition system (typically invoking the interactive debugger).
- Exception values are ordinary first-class Coalton values: they can be constructed in advance, stored in data structures, passed to helper functions, or bound in a
catch/handlebranch and rethrown.
Examples
(coalton-toplevel
(define-exception ParseError
EmptyInput
(InvalidToken String))
(declare parse-token (String -> String))
(define (parse-token s)
(cond
((== s "") (throw EmptyInput))
((== s "?") (throw (InvalidToken s)))
(True s)))
;; Polymorphic helper that logs and rethrows any exception
(declare trace-and-rethrow ((Exception :e) (Show :e) => :e -> :a))
(define (trace-and-rethrow e)
(show e)
(throw e)))
Other notes
throwcompiles directly to(cl:error ⟨exception-expr⟩).- To convert between thrown exceptions and
Resultvalues, usecoalton/result:try(which catches exceptions intoResult) andcoalton/result:ok-or-throw(which unwrapsOkorthrows theErrpayload). - See
define-exception,catch,handle, andprotect.