Python exception chaining(Python 异常链)
问题描述
是否有在 Python 中使用异常链的标准方法?就像由"引起的 Java 异常?
Is there a standard way of using exception chains in Python? Like the Java exception 'caused by'?
这里有一些背景.
我有一个带有一个主要异常类的模块DSError:
I have a module with one main exception class DSError:
class DSError(Exception):
pass
在这个模块的某个地方会有:
Somewhere within this module there will be:
try:
v = my_dict[k]
something(v)
except KeyError as e:
raise DSError("no key %s found for %s" % (k, self))
except ValueError as e:
raise DSError("Bad Value %s found for %s" % (v, self))
except DSError as e:
raise DSError("%s raised in %s" % (e, self))
基本上这个片段应该只抛出 DSError 并告诉我发生了什么以及为什么.问题是 try 块可能会抛出许多其他异常,所以我希望我能做类似的事情:
Basically this snippet should throw only DSError and tell me what happened and why. The thing is that the try block might throw lots of other exceptions, so I'd prefer if I can do something like:
try:
v = my_dict[k]
something(v)
except Exception as e:
raise DSError(self, v, e) # Exception chained...
这是标准的pythonic方式吗?我没有在其他模块中看到异常链,那么在 Python 中是如何完成的?
Is this standard pythonic way? I did not see exception chains in other modules so how is that done in Python?
推荐答案
异常链接只是在 Python 3 中可用,您可以在其中编写:
Exception chaining is only available in Python 3, where you can write:
try:
v = {}['a']
except KeyError as e:
raise ValueError('failed') from e
产生类似的输出
Traceback (most recent call last):
File "t.py", line 2, in <module>
v = {}['a']
KeyError: 'a'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "t.py", line 4, in <module>
raise ValueError('failed') from e
ValueError: failed
在大多数情况下,您甚至不需要 from;默认情况下,Python 3 将显示在异常处理期间发生的所有异常,如下所示:
In most cases, you don't even need the from; Python 3 will by default show all exceptions that occured during exception handling, like this:
Traceback (most recent call last):
File "t.py", line 2, in <module>
v = {}['a']
KeyError: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t.py", line 4, in <module>
raise ValueError('failed')
ValueError: failed
您可以在 Python 2 中为您的异常类添加自定义属性,例如:
What you can do in Python 2 is adding custom attributes to your exception class, like:
class MyError(Exception):
def __init__(self, message, cause):
super(MyError, self).__init__(message + u', caused by ' + repr(cause))
self.cause = cause
try:
v = {}['a']
except KeyError as e:
raise MyError('failed', e)
这篇关于Python 异常链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 异常链
基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
