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

Robert Brewer fumanchu at amor.org
Tue Sep 28 12:38:24 EDT 2004


Michele Simionato wrote:
> I think I want "re-entrant exceptions" (not sure if this is the
> correct name).
> 
> 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? 
> 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 ...

Could you clarify? You say you don't want to rewrite do_this_and_that;
should we assume the rest of the code is open to modification? For
example, the most obvious resolution to me would be to push the try
block into do_this():

class NotSeriousException(Exception):
    pass

def do_this():
    try:
        this_stuff()
    except NotSeriousException:
        pass

def do_that():
    pass

def do_this_and_that():
    do_this()
    do_that()

The other options seem to be: 1) rewrite NotSeriousException, and 2) use
a mechanism other than exceptions to get what you want. But if you can
use another mechanism, that pretty much means (to me) rewriting do_this
to use that mechanism; in that case, you might as well do the above.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list