0

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.)

Community
  • 1
  • 1
Mark
  • 18,730
  • 7
  • 107
  • 130

2 Answers2

1

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • I'm not a big fan of this style but it seems this is the closest way possible – Mark Apr 26 '15 at 10:27
  • @Mark see the update, I added another possible option – vaultah Apr 26 '15 at 10:44
  • Could be useful, but I think often the error handling code isn't related enough to the error object to make it a method. Still, occasionally useful. – Mark Apr 26 '15 at 12:06
-1

You can use nested try-except-blocks:

try:
    try:
        raise A()
    except A:
        print 'A'
        raise
except (A, B):
    print 'A,B'
Daniel
  • 42,087
  • 4
  • 55
  • 81