try-catch-finally
try
catch
finally
8.12

try-catch-finally🔗ℹ

Alex Knauth

A macro for catching exceptions and running teardown operations.

syntax

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

 
catch-clause = (catch pred-expr => handler-expr)
  | (catch (pred-expr id) handler-body ...+)
  | (catch (id) handler-body ...+)
  | (catch _ handler-body ...+)
     
maybe-finally-clause = 
  | (finally post-body ...+)
After evaluating the pred-exprs and handler-exprs, try evaluates the bodys with the new exception handlers, and then evaluates the post-bodys even if execution exits the bodys through an exception or continuation.

Examples:
> (try
    (raise-syntax-error #f "a syntax error")
    (catch (exn:fail:syntax? e)
      (displayln "got a syntax error")))

got a syntax error

> (try
    (raise-syntax-error #f "a syntax error")
    (catch (exn:fail:syntax? e)
      (displayln "got a syntax error"))
    (catch (exn:fail? e)
      (displayln "fallback clause")))

got a syntax error

> (try
    (displayln "at")
    (finally (displayln "out")))

at

out

> (let/cc up
    (try
      (displayln "at before")
      (up (void))
      (displayln "at after")
      (finally (displayln "out"))))

at before

out

syntax

(catch pred-expr => handler-expr)

(catch (pred-expr id) handler-body ...+)
(catch (id) handler-body ...+)
(catch _ handler-body ...+)

syntax

(finally post-body ...+)