Python: Can an exception class identify the object that raised it?
Question: When a Python program raises an exception, is there a way the exception
handler can identify the object in which the exception was raised?

If not, I believe I can find out by defining the exception class like this...

    
    
    class FoobarException(Exception) :
        def __init__(self,message,context) :
            ...
    

...and using it like this:

    
    
        raise FoobarException("Something bad happened!", self)
    

I'd rather not have to pass "self" to every exception, though.


Answer: It quickly gets messy if you want the exception itself to figure out where in
the stack it is. You can do something like this:

    
    
    import inspect
    frameinfo = inspect.getframeinfo(inspect.stack()[1][0])
    caller_name = frameinfo[2]
    file_name = frameinfo[0]
    

This, however, will only really work if you are looking for the function or
method where the exception was raised, not if you are looking for the class
that owns it.

You are probably better off doing something like this:

    
    
    class MyException(Exception):
        pass
    
    # ... somewhere inside a class
        raise MyException("Something bad happened in {}".format(self.__class__))
    

That way you don't have to write any handling code for your `Exception`
subclass either.

