编程语言
首页 > 编程语言> > python – 获取最后抛出的异常的引用

python – 获取最后抛出的异常的引用

作者:互联网

python和/或ipython交互式解释器中,如何在最后一个未处理的异常上绑定名称?即相当于

>>> try:
...     1/0
... except Exception as potato:
...     pass
... 
>>> format(potato)
'integer division or modulo by zero'

必须像……

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> import sys
>>> potato = ???

解决方法:

您可以使用sys.last_value

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> sys.last_value
ZeroDivisionError('integer division or modulo by zero',)
>>> type(sys.last_value)
<type 'exceptions.ZeroDivisionError'>

标签:python,exception,exception-handling,stack-trace,callstack
来源: https://codeday.me/bug/20190517/1123246.html