PythonPython错误代码
ExceptionGroup
ExceptionGroup
这是什么问题?
代码 ExceptionGroup · Python 报告的问题。
译文说明
这两种异常类型都将异常包装在序列 excs 中。 msg 参数必须是字符串。这两个类的区别在于,BaseExceptionGroup 扩展了 BaseException,它可以包装任何异常,而 ExceptionGroup 扩展了 Exception,它只能包装 Exception 的子类。这种设计是为了让 except Exception 捕获 ExceptionGroup 而不是 BaseExceptionGroup。
如果所有包含的异常都是 Exception 实例,则 BaseExceptionGroup 构造函数将返回 ExceptionGroup 而不是 BaseExceptionGroup,因此它可用于自动进行选择。另一方面,如果任何包含的异常不是 Exception 子类,则 ExceptionGroup 构造函数将引发 TypeError。
异常组对于其所包含的异常的类型是通用的。
请注意,BaseExceptionGroup 定义了 __new__(),因此需要不同构造函数签名的子类需要重写它而不是 __init__()。例如,以下定义了一个异常组子类,它接受 exit_code 并从中构造该组的消息。
与 ExceptionGroup 一样,BaseExceptionGroup 的任何子类(也是 Exception 的子类)只能包装 Exception 的实例。
Google Translate · 此内容为自动翻译。技术术语及适用条件请以英文原文为准。
官方说明 · 原文
Both of these exception types wrap the exceptions in the sequence excs. The msg parameter must be a string. The difference between the two classes is that BaseExceptionGroup extends BaseException and it can wrap any exception, while ExceptionGroup extends Exception and it can only wrap subclasses of Exception. This design is so that except Exception catches an ExceptionGroup but not BaseExceptionGroup.
The BaseExceptionGroup constructor returns an ExceptionGroup rather than a BaseExceptionGroup if all contained exceptions are Exception instances, so it can be used to make the selection automatic. The ExceptionGroup constructor, on the other hand, raises a TypeError if any contained exception is not an Exception subclass.
Exception groups are generic over the type of their contained exceptions.
Note that BaseExceptionGroup defines __new__(), so subclasses that need a different constructor signature need to override that rather than __init__(). For example, the following defines an exception group subclass which accepts an exit_code and constructs the group’s message from it.
Like ExceptionGroup, any subclass of BaseExceptionGroup which is also a subclass of Exception can only wrap instances of Exception.
故障排除与诊断链接
请先确认文档中的产品、版本及发生环境与当前情况一致。
- 代码参考
异常与警告的官方说明 ↗
定义与说明 · 非故障排除步骤
- 通用诊断指南
解读异常回溯与处理异常 ↗
适用于整个产品 · 非该代码专用
来源与使用条款
Built-in Exceptions — Python 3.15.2 documentation ↗
作者:Python Software Foundation
许可证:Python Software Foundation License Version 2
核查日期:2026-11-12
修改记录:English prose extracted; whitespace normalized; Korean context and classified official links added. Python code examples not redistributed. 译文说明已标注为自动翻译。