在Python中如何查找引发异常的位置 [英] How in Python find where exception was raised

查看:357
本文介绍了在Python中如何查找引发异常的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定在哪个函数中引发了异常。例如,存在两个功能: foo和 bar。

How to determine in what function exception was raised. For example exist two functions: 'foo' and 'bar'. In 'foo' exception will raised randomly.

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]

这篇关于在Python中如何查找引发异常的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆