简体   繁体   中英

Why is a multiple parent exception not caught?

I toyed around with an exception hierarchy and realized that an exception subclass with several parents is not caught.

For example:

class Error1(Exception): 
    pass

class Error2(Exception): 
    pass

class MixedError(Error1, Error2): 
    pass

try:
    print('before 1')
    raise Error2()
    print('after 1')

except MixedError:
    print('Caught it with a mixin 1!')

except Exception:
    print('Big catcher here 1!')

This prints:

before 1

Big catcher here 1!

Why is a multiple parent exception not caught?

You have a misunderstanding how exceptions work. Exceptions are cached by parent exception, not by child exceptions:

class Error1(Exception):
    pass

class Error2(Exception):
    pass

class MixedError(Error1, Error2):
    pass

try:
    print('before 1')
    raise MixedError()
    print('after 1')

except Error2:
    print('Caught it with a Error2!')

except Exception:
    print('Big catcher here 1!')

prints:

before 1
Caught it with a Error2!

You never raise MixedError . Also, note that parent classes know nothing about child classes, thus, when raising Error1 or Error2 , you are raising an error using the __str__ from that specific class:

class Error1(Exception): 
   pass

class Error2(Exception): 
   pass

class MixedError(Error1, Error2): 
   pass

try:
   raise MixedError('Error here')
except MixedError:
   print("caught 'MixedError'")

Output:

caught 'MixedError'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM