Python只打印引发异常的回溯



我在try-except块中引发了一个新的异常,并带有额外的消息。因此,不再需要原始异常回溯。是否有任何方法可以删除原始回溯,只打印新引发的异常的回溯?

示例代码(Python 3.6.10(:

try:
10/0
except:
raise Exception('some error')

输出:

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
d:xxxmain.py in 
1 try:
----> 2     10/0
3 except:
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Exception                                 Traceback (most recent call last)
d:xxxmain.py in 
2     10/0
3 except:
----> 4     raise Exception('some error')
Exception: some error

期望输出:

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
d:xxxmain.py in 
2     10/0
3 except:
----> 4     raise Exception('some error')
Exception: some error

我在try-except块中引发了一个新的异常,并添加了额外的消息。因此,不再需要原始异常回溯。

您可以放弃最初的异常,但我会重新考虑这个决定。在Python 3中添加异常原因和上下文的原因是,有关原始异常和堆栈跟踪的信息非常有用。我会明确地将原始异常标记为新异常的原因,这会稍微改变消息:

try:
1/0
except ZeroDivisionError as e:
raise Exception("Oh crud") from e

输出:

Traceback (most recent call last):
File "main.py", line 2, in <module>
1/0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise Exception("Oh crud") from e
Exception: Oh crud

也就是说,如果你真的想抑制关于原始异常的信息,你可以使用None作为新异常的原因:

try:
1/0
except ZeroDivisionError:
raise Exception("Oh crud") from None

输出:

Traceback (most recent call last):
File "main.py", line 4, in <module>
raise Exception("Oh crud") from None
Exception: Oh crud

使用with_traceback

import sys, traceback
try:
10/0
except Exception as exc:
raise  exc.with_traceback(None)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-31-d77f0aded0d7> in <module>()
3     10/0
4 except Exception as exc:
----> 5     raise  exc.with_traceback(None)
ZeroDivisionError: division by zero

如果你只想展示它:

import sys, traceback
try:
10/0
except Exception:
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
File "<ipython-input-4-1283199eb169>", line 3, in <module>
10/0

替代

import sys, traceback
try:
10/0
except Exception as exc:
tb_str = traceback.format_exception(etype=type(exc), value=exc, tb=exc.__traceback__)
for i in tb_str: print(i)
Traceback (most recent call last):
File "<ipython-input-17-3bc95dc2ebf5>", line 3, in <module>
10/0
ZeroDivisionError: division by zero

最新更新