[racket] with-handlers and exception structure

From: Gregory Woodhouse (gregwoodhouse at me.com)
Date: Mon Sep 3 21:36:38 EDT 2012

Thanks! That looks very useful. In fact, it could have saved me fair amount of debugging time on my Sudoku program (now playable, but pretty bare bones). 

Sent from my iPhone

On Sep 3, 2012, at 2:44 PM, Greg Hendershott <greghendershott at gmail.com> wrote:

> To add to what Matthew and Danny said, in addition to using
> `exn-message' you can show a "stack trace" if you wish. For example:
> 
> (define (exn->string exn)
>  (string-append "Exception: " (exn-message exn)))
> 
> (define (exn+stack->string exn)
>  (string-append (exn->string exn) "\n"
>                 "Stack:\n"
>                 (stack-trace-string exn)))
> 
> (define (stack-trace-string exn)
>  (string-join
>   (map (lambda (x)
>          (format "'~a' ~a ~a"
>                  (if (car x) (car x) "")
>                  (if (cdr x) (srcloc-source (cdr x)) "")
>                  (if (cdr x) (srcloc-line (cdr x)) "")))
>        (continuation-mark-set->context (exn-continuation-marks exn)))
>   "\n"))
> 
> ;; Example usage:
> (with-handlers ([exn:fail? (compose1 displayln exn+stack->string)])
>  (/ 1 0))
> 
> 
> On Mon, Sep 3, 2012 at 10:56 AM, Danny Yoo <dyoo at hashcollision.org> wrote:
>> 
>> 
>> On Monday, September 3, 2012, Gregory Woodhouse wrote:
>>> 
>>> Dumb question: If an exception is handled by (lambda (e) ... ) is it
>>> possible to recover exception details such as any message that may have been
>>> used in a raise or related statement?
>> 
>> 
>> Hi Gregory,
>> 
>> The value raised by exceptions should be structured; in most cases, the
>> exception value will be an instance of the exn:fail struct.  Take a look at
>> http://docs.racket-lang.org/reference/exns.html#(part._.Built-in_.Exception_.Types)
>> for the definition of the exn struct.  The exn-message function, in
>> particular, should let you select out the string message associated to the
>> raised exception.
>> 
>> ____________________
>>  Racket Users list:
>>  http://lists.racket-lang.org/users
>> 

Posted on the users mailing list.