catching exceptions from an except: block
Gerard Flanagan
grflanagan at yahoo.co.uk
Thu Mar 8 04:17:37 EST 2007
On Mar 7, 7:32 pm, "Arnaud Delobelle" <arno... at googlemail.com> wrote:
> Hi all,
>
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception. Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
>
(This is my first decorator.) You could also just raise your custom
exception rather than having a "retval". Other variations I'm sure are
possible. HTH.
import exceptions
class ABCException(exceptions.Exception):
pass
def onfail(retval):
def outer(fn):
def inner(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
return retval
return inner
return outer
@onfail(False)
def a(x):
if x == 1:
return 'function a succeeded'
else:
raise
@onfail(False)
def b(x):
if x == 2:
return 'function b succeeded'
else:
raise
@onfail(False)
def c(x):
if x == 3:
return 'function c succeeded'
else:
raise
def doit(x):
for f in [a, b, c]:
result = f(x)
if result:
return result
raise ABCException()
print doit(1)
print doit(2)
print doit(3)
print doit(4)
---------------------------
function a succeeded
function b succeeded
function c succeeded
Traceback (most recent call last):
File "\working\scratch.py", line 48, in ?
print doit(4)
File "\working\scratch.py", line 43, in doit
raise ABCException()
__main__.ABCException
shell returned 1
More information about the Python-list
mailing list