【发布时间】:2021-07-26 17:37:30
【问题描述】:
我有以下代码
def _raise_exception(exception):
raise exception
def require_odd(n):
if n % 2 == 0:
_raise_exception(ValueError("n must be odd"))
print(require_odd(2))
当我运行它时,它会显示
Traceback (most recent call last):
File "main.py", line 31, in <module>
print(require_odd(2))
File "main.py", line 29, in require_odd
_raise_exception(ValueError("n must be odd"))
File "main.py", line 25, in _raise_exception
raise exception
ValueError: n must be odd
由于回溯的最后一行代码是多余的,我该如何引发异常以使其显示以下内容?
Traceback (most recent call last):
File "main.py", line 31, in <module>
print(require_odd(2))
ValueError: n must be odd
目前,我正在这样做:
def _raise_exception(exception):
try:
raise exception
except Exception as e:
# Remove the last two calls (from this function and from the caller of this function)
stack_lines = traceback.format_stack()[:-2]
# Get the exception lines that contains the "Traceback (most recent call last):" in
# the first line and the "ValueError: n must be odd" in the last line
exception_lines = traceback.format_exception(e.__class__, e, e.__traceback__)
# Join the relevant lines, print to stderr and exit
print(''.join(exception_lines[:1] + stack_lines + exception_lines[-1:]), file=sys.stderr)
exit(1)
def require_odd(n):
if n % 2 == 0:
_raise_exception(ValueError("n must be odd"))
print(require_odd(2))
确实可以打印
Traceback (most recent call last):
File "main.py", line 31, in <module>
print(require_odd(2))
ValueError: n must be odd
但它只是感觉临时。有没有更好的办法?
【问题讨论】:
-
我不确定您所说的“冗余”是什么意思。堆栈跟踪是人们希望的功能 - 它正在转储整个调用堆栈。这通常被认为是好事,Python 运行时会遇到很多麻烦才能为您提供这些信息...
标签: python error-handling traceback