如何确定引发的异常函数。例如,存在两个函数:'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" % ???
答案 0 :(得分:6)
import inspect
try:
foo()
except Exception as e:
print "Exception raised in %s" % inspect.trace()[-1][3]
答案 1 :(得分:3)
我使用跟踪模块,如下所示:
import traceback
try:
1 / 0
except Exception:
print traceback.format_exc()
这给出了以下输出:
Traceback (most recent call last):
File "<ipython-input-3-6b05b5b621cb>", line 2, in <module>
1 / 0
ZeroDivisionError: integer division or modulo by zero
如果代码从文件运行,则回溯将告诉错误发生的位置的行和字符数:)
修改强>
以适应Habibutsu:Yes, it's useful for printing, but when needed to get more info (for example function name) - not suitable
doc-pages告诉您如何以编程方式提取跟踪:http://docs.python.org/2/library/traceback.html
从上面链接的页面:
>>> import traceback
>>> def another_function():
... lumberstack()
...
>>> def lumberstack():
... traceback.print_stack()
... print repr(traceback.extract_stack())
... print repr(traceback.format_stack())
...
>>> another_function()
File "<doctest>", line 10, in <module>
another_function()
File "<doctest>", line 3, in another_function
lumberstack()
File "<doctest>", line 6, in lumberstack
traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
('<doctest>', 3, 'another_function', 'lumberstack()'),
('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
[' File "<doctest>", line 10, in <module>\n another_function()\n',
' File "<doctest>", line 3, in another_function\n lumberstack()\n',
' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
traceback.extract_stack
的文档字符串与traceback.extract_tb
traceback.extract_tb(traceback [,limit])
返回最多限制“预处理”堆栈跟踪条目的列表 从traceback对象traceback中提取。它很有用 堆栈跟踪的替代格式。如果省略limit或None,则全部 提取条目。 “预处理”堆栈跟踪条目是a 四倍(文件名,行号,函数名,文本)代表 通常为堆栈跟踪打印的信息。文字是 剥离前导和尾随空格的字符串;如果来源 不可用它是无。
答案 2 :(得分:2)
你的目标是什么?如果您担心bar
和foo
抛出相同的异常类型且调用者无法区分它们,只需派生一个新的异常类:
import random
class FooException(Exception):
"""An exception thrown only by foo."""
def foo():
if random.randint(1,10) % 2:
raise FooException
bar()
def bar():
raise Exception
try:
foo()
except FooException:
print "Exception raised in foo..."
except:
print "Exception raised in bar (probably)..."