Is it possible to write an exception handler to catch the run-time errors generated by ALL the methods in class? I can do it by surrounding each one with try/except:
class MyError(Exception):
def __init__(self, obj, method):
print 'Debug info:', repr(obj.data), method.__name__
raise
class MyClass:
def __init__(self, data):
self.data = data
def f1(self):
try:
all method code here, maybe failing at run time
except:
raise MyError(self, self.f1)
I wonder if is there a more general way to achieve the same - for any error raising anywhere in the class. I would like to be able to access the class data to print some debug info. Also, how do I get the failing method name (f1 in the example)?
Update: thanks to all for the insighful answers, the decorator idea looks like the way to go.
About the risk of trapping ALL the exceptions: a raise
statement in the except
branch should re-raise the exception without losing any information, doesn't it? That's why I put it in MyError also...
f1()
gets an IOError, it should report as a MyError? That's bound to lose information and confuse. See blog.ianbicking.org/2007/09/12/re-raising-exceptions for detail. – Rialto