Exceptions as a Control Structure

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Aug 9 10:34:17 EDT 2004


> > Exceptions are also used by some as a mechanism for
> > returning information from subroutines, though it's
> > very likely the information will still be considered
> > "exceptional" in some way (think of it as an out-of-band
> > mechanism for returning special info).
>
> Do you have some example of this in the standard library ?
>

pyparsing uses this technique to try various parse expressions - a raised
ParseException denotes that the attempted parsing pattern failed to match at
the current stream location.

In an earlier incarnation of this library, I implemented this by returning
True or False values to indicate successful matching, but when a False was
returned, I found I needed more information about why things were False.
The exception-based approach allows me to return a full exception, including
the match failure message and the location at which the failure occurred.

One optimization I have found w.r.t. exceptions is that, in pyparsing, a
given parsing expression always raises the almost the same exception, with
only the input location changing.  I found a significant improvement by
pre-constructing the exception at grammar construction time, and then
raising a modified version at parse time.  (Contrast with the dynamic
construction/garbage-collection of thousands of exception objects when
created and used only once.)

-- Paul





More information about the Python-list mailing list