[plt-scheme] Problem understanding exception handlers
At Tue, 17 Sep 2002 13:02:43 +0200, Erich Rast wrote:
> 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?
In the second example, the error happens *before* the call to
`z-parse'. MzScheme fails when trying to parse the call to `z-parse',
because "\#" is not a well-formed string constant.
I expect that `z-parse' does exactly what you want it to do:
> (z-parse "# oops")
an error#f
Matthew