一尘不染

Python异常链接

python

有没有在Python中使用异常链的标准方法?就像Java异常“引起”一样?

这是一些背景。

我有一个具有一个主要异常类的模块DSError

 class DSError(Exception):
     pass

在此模块中的某处将有:

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块可能会引发许多其他异常,因此我更愿意执行以下操作:

try:
    v = my_dict[k]
    something(v)
except Exception as e:
    raise DSError(self, v, e)  # Exception chained...

这是标准的pythonic方法吗?我没有在其他模块中看到异常链,那么如何在Python中完成?


阅读 165

收藏
2020-12-20

共1个答案

一尘不染

异常链接仅在Python 3中可用,您可以在其中编写:

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将显示异常处理期间发生的所有异常,如下所示:

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中执行的操作 是向您的异常类添加自定义属性,例如:

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)
2020-12-20