Search code examples
pythonexceptioncoding-styleparadigms

Python one exception multiple handlers


I want to do this:

try:
    raise A()
except A:
    print 'A'
except (A, B):
    print 'A,B'

Which I hoped would print both A and A,B.

That doesn't work (only the first except is executed). It makes sense for the first except to swallow the error, in case you want to catch a subclass before it's parent.

But is there another elegant way to get this to work?

I could of course do the following, but that is seemingly redundant code duplication, especially if more than just A and B are involved:

try:
    raise A()
except A:
    print 'A'
    print 'A,B'
except B:
    print 'A,B'

(Related to Multiple exception handlers for the same Exception but not a duplicate. The usage is different and I want to know how best to handle it with minimal code duplication.)


Solution

  • It's rather common to catch possible exceptions and get exception type from the instance later:

    try:
        raise A()
    except (A, B) as e:
        if isinstance(e, A):
            print('A')
        print('A', 'B')
    

    Another option is to inherit one class from another e.g.

    class B(Exception):
        def do(self):
            print('A', 'B')
    
    class A(B, Exception):
        def do(self):
            print('A')
            super().do()
    

    Then

    try:
        raise B()
    except (A, B) as e:
        e.do()
    

    will print A B, and

    try:
        raise A()
    except (A, B) as e:
        e.do()
    

    will print A and A B.