[plt-scheme] Problem understanding exception handlers

From: Erich Rast (Erich.Rast at t-online.de)
Date: Tue Sep 17 07:02:43 EDT 2002

I don't understand how with-handlers is supposed to work for installing 
custom exceptions. For my lazyness, I'd like to use the built-in reader 
to parse user-input into a list of symbols or strings. However, I need 
to catch read errors in order to hinder users from crashing my program.

What's wrong with the following code snippet?

; read a string and parse it into its components as a list
; e.g. (z-parse "Person Name "joe hacker"")==>(Person Name "joe hacker")
; return #f if an error has occured
;
(define (z-parse string)
   (with-handlers ([(lambda (exc) #t)
                    (lambda (exc) (display "an error") #f)])
     (let loop ((in (open-input-string string))
                (read-obj ())
                (out ()))
       (cond ((not read-obj) #f)
             ((not (eof-object? read-obj)) (loop in (read in) (cons 
read-obj out)))
             (else (cdr (reverse! out)))))))

(z-parse "Hello world")
==> (Hello world)

but:
(z-parse "\# oops")
==> read: unknown escape sequence \# in string

Shouldn't my custom error handler display "an error" and return #f for 
(read in), thus the whole loop return #f?

Thanks,

Erich




Posted on the users mailing list.