catching exceptions from an except: block

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 9 03:52:35 EST 2007


"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote:

> Not the *previous* exception, but the *current* one. You must be
> inside an  "except" clause to use a bare raise.
> 
No, you don't have to be inside an except clause to use a bare raise.

A bare 'raise' will re-raise the last exception that was active in the 
current scope. That applies even outside the except clauses just so long 
as there has been an exception within the same function:

e.g.

def retry(fn, *args):
    for attempt in range(3):
        try:
            return fn(*args)
        except:
            print "retrying attempt", attempt+1
    # If we get here we've had too many retries
    raise

>>> import random
>>> def testfn():
	if random.randint(0,3):
		raise RuntimeError("oops")
	return 42

>>> retry(testfn)
retrying attempt 1
retrying attempt 2
retrying attempt 3

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    retry(testfn)
  File "<pyshell#20>", line 4, in retry
    return fn(*args)
  File "<pyshell#23>", line 3, in testfn
    raise RuntimeError("oops")
RuntimeError: oops
>>> retry(testfn)
retrying attempt 1
retrying attempt 2
42
>>> retry(testfn)
42



More information about the Python-list mailing list