re-entering in the normal flow after an exception is raised

Bengt Richter bokr at oz.net
Tue Sep 28 20:15:33 EDT 2004


On 28 Sep 2004 09:17:07 -0700, michele.simionato at gmail.com (Michele Simionato) wrote:

>I think I want "re-entrant exceptions" (not sure if this is the
>correct name).
As Alex said, resumable is the usual word, I think.
>
>Consider the following example:
>
>class NotSeriousException(Exception):
>    pass
>
>def do_this():
>    raise NotSeriousException()
>
>def do_that():
>    pass
>
>def do_this_and_that():
>    do_this()
>    do_that()
>
>Since the exception is raised at the do_this() level, do_that() will
>not be executed. However, since the exception is not that serious, I
>would like to catch it and continue from the point the exception was
>raised, i.e. something like that:
>
>try:
>    do_this_and_that()
>except NotSeriousException:
>    continue # does not work of course
>
>where "continue" would continue from do_that().
>
>Is there some elegant or hackish way to get this?
Hacks will probably bite you later, though I think they're fine
for one-time throwaway code that you really throw away.

I wonder if you could interfere with exception unwinding via sys.settrace.
I believe you can get control at each frame as the exception propagates,
but I don't know what can be done. I think you would take a big performance hit though.

>Notice that I do NOT want to modify the source code of
>do_this_and_that.
>It comes from real life code and I could modify it, but if there was
>some
>smarter way of getting what I want I would be interested ...
Maybe think about smart ways to modify?

It comes to mind that you might have functions call a complain function
instead of directly raising exceptions, if you want to customize or parameterize
by seriousness or other criteria. E.g., (untested)

    def complain(kind, exc, *args):
        if kind in globalconfigdict: raise exc(*args)

    def dothis():
        complain('not so serious', NotSeriousException, 'args', 'for', 'exception')

Just an idea. You could also make complain a callable object with various methods for
configuring behaviour easily etc. etc. Just .02USD off the top of my head ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list