Search code examples
exceptiontry-catchlispracket

How to implement try-catch block in racket?


I try to write a try-catch block in racket, from the boilerplate provided here, however when I run it throws me an error.

try-catch block:

#lang racket
 (require try-catch-match)


(try [(displayln "body")
    (raise 'boom)]
   [catch (string? (printf "caught a string: ~v\n" e))
          (symbol? (printf "'e' (the value of the exception) is: ~v\n" e))])

Throws this error:

enter image description here

It says syntax error, but I really cannot see any issues. The code is from the official racket website. My goal is to write a simple try-catch block in racket, presumably using the imported library.


Solution

  • You're requiring try-catch-match library, but your example comes from try-catch library. These two are different and if you use the correct one, the example code will work:

    #lang racket
    (require try-catch)
    
    (try [(displayln "body")
            (raise 'boom)]
           [catch (string? (printf "caught a string\n"))
                  (symbol? (printf "caught a symbol\n"))])