【问题标题】:Can I change "recent call" stack when raise exception in Python?在 Python 中引发异常时,我可以更改“最近调用”堆栈吗?
【发布时间】:2019-06-07 05:52:27
【问题描述】:

当我在代码中引发异常时,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...”代码,我认为这不是必要的信息。怎么隐藏?

【问题讨论】:

    标签: python exception raise


    【解决方案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)
    

    【讨论】:

    • 我想在raise(被调用者代码)时隐藏调用堆栈,但不尝试......除了......(调用者代码)。调用者可能不知道被调用者发生了什么。
    猜你喜欢
    • 2012-10-29
    • 2017-07-26
    • 2014-07-29
    • 1970-01-01
    • 2019-11-05
    • 2015-12-30
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多