首页 > 解决方案 > 希望我的代码引发特定类型或错误,但打印原始错误

问题描述

所以假设我有一些代码会引发任何类型或错误。我希望我的代码改为引发 AssertionError,但打印出原始消息将与原始错误一起打印。我该怎么做?

(例子)

原始错误:TypeError: '>' 在 'str' 和 'int' 的实例之间不支持

自定义错误:AssertionError: exception = TypeError: '>' 在 'str' 和 'int' 的实例之间不支持

标签: pythonpython-3.xerror-handling

解决方案


您正在寻找允许您围绕基本异常包装应用程序特定异常的from语法(在 Python 3 中引入)。这是一个例子:

>>> try:
...     1 > '1'
... except TypeError as e:
...     raise AssertionError() from e
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AssertionError

您可以在创建新异常时提供包含诊断消息的字符串。最好定义自己的应用程序特定异常,而不是回收 AssertionError。如果您定义了多个,请将其中一个设为 [grand] 父级,并让其他异常从该祖先继承。这允许调用者方便地捕获细粒度或粗粒度的错误类。

有一个PEP描述了进一步的考虑。


推荐阅读