在类中捕获异常 [英] Catch exceptions inside a class
问题描述
是否可以编写一个异常处理程序来捕获类中所有方法生成的运行时错误?我可以通过用try / except包围每个对象来做到这一点:
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)
我想知道是否有更通用的方法可以实现相同目的-对于类中任何地方引发的错误。我希望能够访问类数据以打印一些调试信息。
另外,如何获取失败的方法名称(示例中为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)?
更新:感谢大家的支持令人叹为观止的答案,装饰者的想法看起来像是要走的路。
关于捕获所有异常的风险: except
分支中的 raise
语句应重新引发没有丢失任何信息的异常,不是吗?这就是为什么我也将其放在MyError中。
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...
推荐答案
警告:如果您想要这样的东西,很可能您不会...但是如果您真的想要...
类似的东西:
import functools
def catch_exception(f):
@functools.wraps(f)
def func(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
print 'Caught an exception in', f.__name__
return func
class Test(object):
def __init__(self, val):
self.val = val
@catch_exception
def calc():
return self.val / 0
t = Test(3)
t.calc()
显示如何装饰单个功能。然后,您可以创建一个类装饰器,以将该装饰器应用于每种方法(请注意 classmethod的
/ staticmethod /
属性
等...)
shows how to decorate individual functions. You can then create a class decorator to apply this decorator to each method (be careful of classmethod's
/staticmethod's
/properties
etc...)
这篇关于在类中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!