Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in Python find where exception was raised

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" % ???
like image 506
Habibutsu Avatar asked Mar 06 '14 17:03

Habibutsu


1 Answers

import inspect

try:
    foo()
except Exception as e:
    print "Exception raised in %s" % inspect.trace()[-1][3]
like image 63
Habibutsu Avatar answered Sep 27 '22 00:09

Habibutsu