正如标题所解释的,我想创建一个通用异常类,从稍后在其他类中捕获的内置异常类继承
这是我的密码:
from functools import wraps
class ControlledException(TypeError, AttributeError):
"""A generic exception on the program's domain."""
class WithRetry:
def __init__(self, retries_limit=3, allowed_exceptions=None):
self.retries_limit = retries_limit
self.allowed_exceptions = allowed_exceptions or (ControlledException,)
def __call__(self, operation):
@wraps(operation)
def wrapped(*args, **kwargs):
last_raised = None
for _ in range(self.retries_limit):
try:
return operation(*args, **kwargs)
except self.allowed_exceptions as e:
print(f'retrying {operation.__qualname__} due to {e}')
last_raised = e
raise last_raised
return wrapped
@WithRetry()
def test(x):
x = x + 1
print(x)
test('a')
ControlledException
类继承了我想要捕获的两个异常TypeError
和AttributeError
。在这种情况下,程序将捕获TypeError
我不知道为什么参数self.allowed_exceptions
对(可控异常,)没有影响。。。
但是,如果我将(ControlledException,)更改为Exception或TypeError,则会捕获错误
当您这样定义自定义异常时,要么直接
raise
它们,要么捕获原始异常,然后引发自定义异常在这里,我捕获了原始异常,抑制了它们的回溯,并引发了您的自定义异常
这将打印出:
相关问题 更多 >
编程相关推荐