加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在Python中找到引发异常的位置

发布时间:2020-12-20 12:06:03 所属栏目:Python 来源:网络整理
导读:如何确定引发了什么函数异常.例如,存在两个函数:’foo’和’bar’.在’foo’中,异常将随机提出. import randomdef foo(): if random.randint(1,10) % 2: raise Exception bar()def bar(): raise Exceptiontry: foo()except Exception as e: print "Exceptio
如何确定引发了什么函数异常.例如,存在两个函数:’foo’和’bar’.在’foo’中,异常将随机提出.

import random


def foo():
    if random.randint(1,10) % 2:
        raise Exception
    bar()


def bar():
    raise Exception

try:
    foo()
except Exception as e:
    print "Exception raised in %s" % ???

解决方法

import inspect

try:
    foo()
except Exception as e:
    print "Exception raised in %s" % inspect.trace()[-1][3]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读