我正在 Python 中开发一个惰性评估库,它允许用户编写普通代码,同时在稍后的时间点对其进行评估。问题是这些异常非常令人困惑。这就是为什么我想用修改后的堆栈跟踪抛出异常。它应该看起来好像根本没有延迟评估(或者只是有一个简短的提示)就触发了异常。
这是我已经尝试过的。我没有找到更好的方法来获取回溯,但如果可能的话,我宁愿不在 create_tb 中抛出异常。
import sys
def create_tb(): # Capture the stack trace
try:
raise Exception("A")
except:
_, _, tb = sys.exc_info()
return tb
def raise_with_tb(tb): # It should look like "B" was triggered in create_tb
raise Exception("B").with_traceback(tb)
tb = create_tb()
raise_with_tb(tb)
但是输出是:
Traceback (most recent call last):
File ".../test.py", line 16, in <module>
raise_with_tb(tb)
File ".../test.py", line 12, in raise_with_tb
raise Exception("B").with_traceback(tb)
File ".../test.py", line 5, in create_tb
raise Exception("A")
Exception: B
而不是类似:
Traceback (most recent call last):
File ".../test.py", line 5, in create_tb
raise Exception("B")
Exception: B
这可能吗?
我对 Python 比较陌生。如果有更多的植物方式来实现我的目标,我很高兴提出建议。
最佳答案
我找到了一种方法来抑制先前发生的异常的上下文:
try:
raise Exception('original exception message')
except Exception as exc:
my_custom_exception = Exception('my custom message')
my_custom_exception.__suppress_context__ = True
raise my_custom_exception
它给出了以下回溯:
Traceback (most recent call last):
File "ex.py", line 6, in <module>
raise my_custom_exception
Exception: my custom message
使用 my_custom_exception.__suppress_context__ = True
行注释回溯也有以前的异常:
Traceback (most recent call last):
File "ex.py", line 2, in <module>
raise Exception('original exception message')
Exception: original exception message
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "ex.py", line 6, in <module>
raise my_custom_exception
Exception: my custom message
但我不确定它 1) 是 pythonic 方式 2) 是否真的是你所需要的。
关于python - 在抛出之前操作异常的堆栈跟踪 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54781178/