try..yield..finally problem: a proposed solution.

Andrew Bennetts andrew-pythonlist at puzzling.org
Thu Jun 5 16:18:12 CEST 2003


On Thu, Jun 05, 2003 at 03:01:55PM +0100, Alan Kennedy wrote:

[..snip lots of discussion of various code snippets..]

> 
> So, restating the proposed solution, with fully specified code
> 
> #------------------------------
> 
> import random
> 
> class Finality(Exception): pass
> 
> def finfunc():
>     try:
>         try:
>             # Risky code, e.g.
>             for i in range(10):
>                 x = 1/int(random.random()*10)
>                 yield x
>             print "Successful processing"
>             raise Finality
>         except Exception, x:
>             print "Finally"
>             raise x
>     except Finality:
>         pass
>     except Exception, x:
>         print "Told you that code was risky, didn't I?: %s" % str(x)
> 
> for v in finfunc():
>     print v
> 
> #------------------------------

I've almost nothing to add here, except to suggest that instead of "raise
x", just use "raise", which will preserve the full traceback :)

The approach of explicitly raising an exception even if you succeed so that
you *always* enter the except block does indeed solve the problem, by
turning the except into a de facto finally.  I understand what you're doing
now :)

-Andrew.






More information about the Python-list mailing list