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 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
