Generators and propagation of exceptions

Kent Johnson kent37 at tds.net
Sat Apr 9 08:02:43 EDT 2011


On Apr 8, 3:47 pm, r <nbs.pub... at gmail.com> wrote:
> I'm already making something like this (that is, if I understand you
> correctly). In the example below (an "almost" real code this time, I
> made too many mistakes before) all the Expressions (including the
> Error one) implement an 'eval' method that gets called by one of the
> loops. So I don't have to do anything to detect the error, just have
> to catch it and reraise it at each stage so that it propagates to the
> next level (what I have to do anyway as the next level generates
> errors as well).
>
> class Expression(object):
>     def eval(self):
>         pass
>
> class Error(Expression):
>     def __init__(self, exception):
>         self.exception = exception
>
>     def eval(self):
>         raise self.exception

Perhaps, instead of raising exceptions at each level, you could return
an Error object that implements the eval() (or whatever appropriate
protocol) to return an appropriate new Error object. In this case, you
could have
class Error(Expression);
    ....
    def eval(self):
        return unicode(self.exception)

Error would itself be created by Expression.parseToken(), instead of
raising an exception.

The idea is that at each level of parsing, instead of raising an
exception you return an object which, when interpreted at the next
outer level, will again return an appropriate error object for that
level. You might be able to have a single Error object which
implements the required methods at each level to just return self.

I don't know if this really works when you start nesting but perhaps
it is worth a try.

Kent



More information about the Python-list mailing list