catching exceptions from an except: block

Gerard Flanagan grflanagan at
Thu Mar 8 10:17:37 CET 2007

On Mar 7, 7:32 pm, "Arnaud Delobelle" <arno... at> 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):

def onfail(retval):
    def outer(fn):
        def inner(*args, **kwargs):
                return fn(*args, **kwargs)
                return retval
        return inner
    return outer

def a(x):
    if x == 1:
        return 'function a succeeded'

def b(x):
    if x == 2:
        return 'function b succeeded'

def c(x):
    if x == 3:
        return 'function c succeeded'

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\", line 48, in ?
    print doit(4)
  File "\working\", line 43, in doit
    raise ABCException()
shell returned 1

More information about the Python-list mailing list