如果不能具有静态类型参数,则不能具有静态抛出声明。例如,我无法注释此函数:
def throw_me(x):
raise x
甚至这个:
def call_func(f):
f() # f could throw any exception
您可以做的是使抛出除指定异常以外的任何类型的异常都成为错误:
from functools import wraps
class InvalidRaiseException(Exception):
pass
def only_throws(E):
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except E:
raise
except InvalidRaiseException:
raise
except Exception as e:
raise InvalidRaiseException("got %s, expected %s, from %s" % (
e.__class__.__name__, E.__name__, f.__name__)
)
return wrapped
return decorator
@only_throws(ValueError)
def func(x):
if x == 1:
raise ValueError
elif x == 2:
raise Exception
>>> func(0)
>>> func(1)
ValueError
>>> func(2)
InvalidRaiseException: got Exception, expected ValueError, from func