catching exceptions from an except: block
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Wed Mar 7 22:43:47 EST 2007
On Wed, 07 Mar 2007 10:32:53 -0800, Arnaud Delobelle 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.
>
> Here are three ways I can think of doing it:
>
> ----------
> # This one looks ugly
> def nested_first(x):
> try:
> return a(x)
> except:
> try:
> return b(x)
> except:
> try:
> return c(x)
> except:
> raise CantDoIt
Exceptions are great, but sometimes they get in the way. This is one of
those times.
NULL = object() # get a unique value
def result_or_special(func, x):
"""Returns the result of func(x) or NULL."""
try:
return func(x)
except Exception:
return NULL
def failer(x):
"""Always fail."""
raise CantDoIt
def function(x):
funcs = (a, b, c, failer)
for func in funcs:
result = func(x)
if result is not NULL: break
return result
Or if you prefer:
def function(x):
NULL = object()
funcs = (a, b, c)
for func in funcs:
try:
result = func(x)
except Exception:
pass
else:
break
else:
# we didn't break out of the loop
raise CantDoIt
# we did break out of the loop
return result
--
Steven D'Aprano
More information about the Python-list
mailing list