我需要进行一系列调用,所有调用都会引发异常,我想要一种保护调用的好方法。我试图找到一种更专业的方式在python中执行以下操作:
def protected_call(method):
result = None
try:
result= method()
except: pass
return result
class Test():
def terminate():
protected_call(self.could_throw_exception)
protected_call(self.receiver.stop)
protected_call(self.connection.stop)
#etc
有更好的方法吗?也许带注释?
为了澄清,我不想要在原始方法上添加注释,即:
class Receiver():
@protected
def stop():
print 'I dont want to do this'
class Test():
@protected
def could_throw_exception():
print 'dont want this'
def stop():
self.could_throw_exception()
self.receiver.stop()
这就是我想要的:
class Receiver():
def stop():
print 'I want this'
class Test():
def could_throw_exception():
print 'like this'
'''This one cares about crashing'''
def stop()
self.could_throw_exception()
self.receiver.stop()
self.connection.stop()
'''This one does not'''
def terminate():
#i want to define it at the call level.
@protected
self.could_throw_exception()
@protected
self.receiver.stop()
答案 0 :(得分:3)
装饰师将是完美的:
def protected_call(method):
def wrapper(*args, **kwargs):
try:
return method(*args, **kwargs)
except:
pass
return wrapper
样本用法:
@protected_call
def foo():
raise Exception()
# nothing is being raised
foo()
答案 1 :(得分:3)
正如nmichaels所说,这种事情最好通过with
声明处理。
@contextlib.contextmanager
def suppress_exceptions(*exceptions):
if not exceptions:
exceptions = Exception
try:
yield
except exceptions:
# You would log an error here
# If you have logging in your application
pass
with suppress_exceptions():
1/0
print("Ignored the exception!")
with suppress_exceptions(IOError):
1/0
# The second one will let the exception through
答案 2 :(得分:1)
听起来像装饰工作
def protected_call(func):
def inner(*args, **kw):
try:
return func(*args, **kw)
except:
pass
return inner
class Test():
@protected_call
def throws_exception(self):
print 1/0
@protected_call
def no_exception(self):
print 4
def sometimes_need_exception(self):
print 5
protected_sometimes_need_exception = protected_call(sometimes_need_exception)
def stop(self):
self.throws_exception()
self.no_exception()
答案 3 :(得分:0)
至少记录异常似乎是一个有用的功能,或者你如何控制意外错误......?