try-catch-match
try
catch
finally
try-with
try-with*
8.12

try-catch-match🔗ℹ

Benedek Szilvasy

A try-catch-finally macro that binds with match.

syntax

(try body ...+ catch-clause ... maybe-finally-clause)

 
catch-clause = (catch pat body ...+)
     
maybe-finally-clause = 
  | (finally body ...+)
try to evaluate body expressions, returning the last one on success.

If an exception is raised, then attempt to match one of the pats in the catch clauses, returning the result of its body. If none of them match, the exception is re-raised.

If there is a finally clause present, it will be executed when exiting the body, through a normal return, uncaught exception or a continuation.

syntax

(catch pat body ...+)

A catch clause, executes and returns body if pat matches a raised exception.

syntax

(finally body ...+)

Evaluated before try returns.

Examples:
> (try
   (raise "raised string")
   (catch (? string? e)
     (display "Caught: " (current-error-port))
     (displayln e (current-error-port))))

Caught: raised string

> (try
   (cons 1)
   (catch (or (? exn? (app exn-message msg))
              (app ~a msg))
     msg))

"cons: arity mismatch;\n the expected number of arguments does not match the given number\n  expected: 2\n  given: 1"

> (displayln
   (call/cc
    (lambda (cc)
      (try
       (cc "Escaped")
       (finally
        (displayln "Escaping"))))))

Escaping

Escaped

syntax

(try-with ([id val] ...) body ...+)

Like let, bind ids to vals in body. vals are evaluated with current-custodian set to a new custodian created with make-custodian. When the expression returns, the custodian is shutdown with custodian-shutdown-all in a finally clause.

Example:
> (custodian-box-value
   (try-with ([b (make-custodian-box (current-custodian) 'x)])
     (displayln (custodian-box-value b))
     b))

x

#f

syntax

(try-with* ([id val] ...) body ...+)

Like try-with, but the binding of each id is made available in subsequent vals, as in let*. All vals are evaluated with the same custodian.