0

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.

Jonathan Sachs
  • 613
  • 8
  • 19
  • See: http://stackoverflow.com/questions/1497683/can-python-determine-the-class-of-a-object-accessing-a-method/1497768#1497768 AND: http://stackoverflow.com/questions/7272326/introspect-calling-object – jmunsch Jul 28 '16 at 17:54

1 Answers1

0

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.

Dr K
  • 416
  • 2
  • 5
  • Thank you for the information, but the solution looks worse than the problem -- a case of "possible, but not sensible"! I tried my proposed fallback approach. It works well enough, and I'm moving on. – Jonathan Sachs Jul 28 '16 at 21:52
  • Yeah, I agree. The cases where you want to actually use code like this is pretty rare :) – Dr K Jul 28 '16 at 21:59