您可以设置exc.__cause__ = None
在 Python 3.3 中抑制上下文打印:
except re.error as e:
e_msg = 'Regular expression error in "{}"'.format(regex)
e_reraise = Exception(e_msg)
e_reraise.__cause__ = None # 'raise e_reraise from None'
raise e_reraise
在 Python 3.3 中,当您使用raise exc from cause
真正发生的是:
exc.__cause__ = cause
raise exc
和设置exc.__cause__
依次隐式设置exc.__suppress_context__ = True
. See PEP 415 http://www.python.org/dev/peps/pep-0415/,其中详细说明了如何raise exc from None
被处理。
当你设置exc.__cause__ = None
在 Python 3.2 中,没有任何变化:
$ python3.2
Python 3.2.3 (default, Apr 13 2012, 13:31:19)
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
... raise ValueError()
... except:
... exc = TypeError()
... exc.__cause__ = None
... raise exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError
但在 Python 3.3 中,上下文被抑制了:
$ python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:08)
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
... raise ValueError()
... except:
... exc = TypeError()
... exc.__cause__ = None
... raise exc
...
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError
就像你用过一样raise exc from None
:
>>> try:
... raise ValueError()
... except:
... raise TypeError() from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError