【问题标题】:How can I change exception position?如何更改异常位置?
【发布时间】:2021-05-23 07:16:19
【问题描述】:

我想在我的代码中引发自定义异常,但显示了不必要的堆栈信息。

简单代码:

def func1(val):
    if isinstance(val, int) is True:
        print('value:', val)
    else:
        raise TypeError('must be integer')

def func2():
    func1(1)
    func1('1')

func2()

结果:

value: 1
Traceback (most recent call last):
  File "c:/Users/sss/etc/exceptionTest/exceptionTest.py", line 17, in <module>
    func2()
  File "c:/Users/sss/etc/exceptionTest/exceptionTest.py", line 14, in func2
    func1('1')
  File "c:/Users/sss/etc/exceptionTest/exceptionTest.py", line 9, in func1
    raise TypeError('must be integer')
TypeError: must be integer

最后一个堆栈是raise 代码所在的位置,它不是必需的。我怎样才能删除它?

【问题讨论】:

  • 虽然您可以删除堆栈跟踪,但处理此问题的正确方法是捕获异常、处理它并打印要显示的异常部分。

标签: python exception traceback raise


【解决方案1】:

您可以将sys.tracebacklimit 设置为-1

import sys
sys.tracebacklimit = -1

def func1(val):
    if isinstance(val, int):
        print('value:', val)
    else:
        raise TypeError('must be integer')

def func2():
    func1(1)
    func1('1')

func2()

输出:

value: 1
Traceback (most recent call last):
** IDLE Internal Exception: 
TypeError: must be integer

或者如果您仍然希望能够看到错误的来源,请将sys.tracebacklimit 设置为3

value: 1
Traceback (most recent call last):
  File "C:/Users/wil/Desktop/dsvcax.py", line 14, in <module>
    func2()
  File "C:/Users/wil/Desktop/dsvcax.py", line 12, in func2
    func1('1')
TypeError: must be integer

请注意,if isinstance(val, int) is True: 可以缩短为 if isinstance(val, int):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-06
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多