为何多父类派生的异常无法捕获其父类异常实例?
Great question! Let's break down exactly why this happens in Python:
Core Rule of Python Exception Handling
Python's exception catching works by checking if the raised exception instance is an instance of (or subclass of) the exception class listed in the except clause. In other words:
- If you raise
ChildError(), it can be caught byexcept ParentError:(sinceChildErroris a subclass ofParentError) - But if you raise
ParentError(), it cannot be caught byexcept ChildError:(becauseParentErroris not a subclass ofChildError)
Applying This to Your Code
Let's map this to your example:
MixedErrorinherits from bothError1andError2, soissubclass(MixedError, Error2)returnsTrue- However, the instance you're raising is
Error2()— when we checkisinstance(Error2(), MixedError), this returnsFalse
That's the key! The except MixedError: clause only catches instances that are either:
- Directly
MixedErrorinstances, or - Instances of subclasses of
MixedError
Since Error2 is the parent class of MixedError, not a child, its instances don't match the MixedError type check.
Test This Yourself
If you add a quick check to your code, you'll see this clearly:
print(isinstance(Error2(), MixedError)) # Output: False print(isinstance(MixedError(), Error2)) # Output: True
Fixing the Behavior
If you want the except MixedError: clause to trigger, you need to raise a MixedError instance instead:
try: print('before 1') raise MixedError() # Changed from Error2() print('after 1') except MixedError: print('Caught it with a mixin 1!') except Exception: print('Big catcher here 1!')
This will output: before 1 Caught it with a mixin 1!
Alternatively, if you want to catch Error2 instances, use except Error2: directly instead of relying on the subclass.
内容的提问来源于stack exchange,提问作者Jon

