在Python中引发异常时,可以更改“最近调用”堆栈吗?

时间:2019-06-07 05:52:27

标签: python exception raise

当我在代码中引发异常时,Python显示调用堆栈。最后一个调用是我编写的引发异常代码的地方。但这本身并不是重要的代码。 我可以更改调用堆栈以隐藏“ raise ...”代码吗?

我的代码:

def myFunc(var):
  if isinstance(var, int) is True:
    print('var:', var)
  else:
    raise TypeError('Invalid type.')


def wrapperFunc(var):
  myFunc(var)


if __name__ == '__main__':
  wrapperFunc('abc')

结果:

Traceback (most recent call last):
  File "C:/Users/snoma/study/python/etc/trackImageEdge/exceptTest.py", line 13, in <module>
    wrapperFunc('abc')
  File "C:/Users/snoma/study/python/etc/trackImageEdge/exceptTest.py", line 9, in wrapperFunc
    myFunc(var)
  File "C:/Users/snoma/study/python/etc/trackImageEdge/exceptTest.py", line 5, in myFunc
    raise TypeError('Invalid type.')
TypeError: Invalid type.

最后一个调用是“ raise TypeError ...”代码,我认为这不是必需的信息。我怎么藏起来?

1 个答案:

答案 0 :(得分:1)

您可以使用traceback模块来限制回溯中的信息

import sys
import traceback

def c():
  a = 1/0

def b():
  c()

def a():
  b()

try:
  a()
except:
  t, v, bt = sys.exc_info()
  traceback.print_tb(bt, limit=2)
  traceback.print_tb(bt)

使用堆栈跟踪

您可以尝试使用堆栈形状,但我认为无法消除导致错误的最初原因

import sys
import traceback

def c(): 1/0
def b(): c()
def a(): b()


t = None
v = None
bt = None

try:
  a()
except:
  t, v, bt = sys.exc_info()

bt = None  # you can play here with changing bt.tb_next order

raise exc.with_traceback(bt)