python - 为什么没有捕获到多父异常?

标签 python exception

我玩弄了一个异常层次结构并意识到 未捕获具有多个父类的异常子类。

例如:

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!')

这打印:

before 1

Big catcher here 1!

为什么没有捕获到多父异常?

最佳答案

您误解了异常 的工作原理。异常由父异常缓存,而不是由子异常缓存:

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!')

打印:

before 1
Caught it with a Error2!

关于python - 为什么没有捕获到多父异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50136746/

相关文章:

python - 转换 pandas.DataFrame 中的元组列表

python - flask .cli.NoAppException : Application crashing

python - 如何在 Python 中展平 XML 文件

java - 使用流的流

database - 哪个更好 : Catching database exception or creating manual check?

python - 帮助访问Python函数内的模块变量?

python - 在 post_save 信号中访问用户的请求

java - 为什么在尝试从列表中删除元素时会收到 UnsupportedOperationException?

java - 创建自定义异常类

mysql - 打开连接时发生内部连接 fatal error