handle evaluates an expression and intercepts matching thrown exceptions in-place before unwinding the stack, allowing handler branches to invoke resume-to.
Syntax
(handle ⟨expr⟩
⟨handle-branch⟩+)
;; ⟨handle-branch⟩ := ((⟨exception-ctor⟩ ⟨pattern⟩*) ⟨body-element⟩* ⟨expr⟩)
;; | ((the ⟨exception-type⟩ ⟨var-or-_⟩) ⟨body-element⟩* ⟨expr⟩)
;; | (_ ⟨body-element⟩* ⟨expr⟩)
Semantics
handleuses the same branch pattern syntax and top-to-bottom matching rules ascatch. If no branch matches a thrown exception, the exception propagates to outer handlers without unwinding.- Unlike
catch, a matchinghandlebranch runs in-place at the point where the exception was thrown, before the stack unwinds:- The branch can transfer control via
resume-toto a resumption established inside⟨expr⟩byresumable. - The branch observes the dynamic bindings (
dynamic-bind) in effect at thethrowsite. - Because the signaling frames are still on the stack while the branch runs,
handlebranches are not in tail position.
- The branch can transfer control via
- If a matching branch completes normally (without calling
resume-toorthrow), the stack unwinds to thehandleexpression and the branch’s value(s) are returned fromhandle. - Exceptions thrown inside a
handlebranch propagate to handlers enclosing thehandle. ⟨expr⟩and all branch bodies must unify to the same result type, which may be a single value,Void, or multiple values.
Examples
(coalton-toplevel
(define-exception BadEgg
(DeadlyEgg String))
(define-resumption SkipEgg)
(declare make-breakfast-with (String -> (Optional String)))
(define (make-breakfast-with egg)
(resumable
(if (== egg "rotten")
(throw (DeadlyEgg egg))
(Some (<> "cooked " egg)))
((SkipEgg) None)))
(declare make-breakfast-or-skip (String -> (Optional String)))
(define (make-breakfast-or-skip egg)
(handle (make-breakfast-with egg)
((DeadlyEgg _) (resume-to SkipEgg)))))
(coalton
(Tuple (make-breakfast-or-skip "fresh")
(make-breakfast-or-skip "rotten")))
; => #.(TUPLE "cooked fresh" #.NONE)
Other Notes
- Prefer
catchunless a handler branch needs to invokeresume-toor inspect dynamic state from the throw site. handlecompiles to Common Lispcl:handler-bindwhere the handler body runs directly inside the condition handler function and returns from the enclosingcl:blockif it finishes normally.- See
catch,resumable,resume-to, andthrow.