You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何多父类派生的异常无法捕获其父类异常实例?

Why can't a multi-inheritance exception subclass catch its parent exception instance?

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 by except ParentError: (since ChildError is a subclass of ParentError)
  • But if you raise ParentError(), it cannot be caught by except ChildError: (because ParentError is not a subclass of ChildError)

Applying This to Your Code

Let's map this to your example:

  • MixedError inherits from both Error1 and Error2, so issubclass(MixedError, Error2) returns True
  • However, the instance you're raising is Error2() — when we check isinstance(Error2(), MixedError), this returns False

That's the key! The except MixedError: clause only catches instances that are either:

  • Directly MixedError instances, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:21:49