python - 希望我的代码引发特定类型或错误,但打印原始错误
问题描述
所以假设我有一些代码会引发任何类型或错误。我希望我的代码改为引发 AssertionError,但打印出原始消息将与原始错误一起打印。我该怎么做?
(例子)
原始错误:TypeError: '>' 在 'str' 和 'int' 的实例之间不支持
自定义错误:AssertionError: exception = TypeError: '>' 在 'str' 和 'int' 的实例之间不支持
解决方案
您正在寻找允许您围绕基本异常包装应用程序特定异常的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描述了进一步的考虑。
推荐阅读
- sql-server - 将包含 select 的 where 子句转换为 Linq
- azure-maps - 用于 azure 地图切换地图视图的文档
- apache-spark - 停止 Spark 会话不会关闭 Metastore mysql 连接
- android - 将图像添加到android中的工具栏
- c++ - c++ OpenCV 如何在超像素上使用 EM 算法?
- pdf - 如何检查 .xsig 签名的有效性?
- docker - DiskSpaceHealthIndicator 报告用户在 Docker 中运行的 0 个字节可用
- python - 太多的值无法解压 python3
- email - 如何使用机器人框架获取电子邮件正文?
- spring - Spring Data JPA Query - 使用 in 子句计数