Can I use it in a scene where I have defined exceptions for the library and it's a hassle to wrap built-in exceptions?
import functools
class MyException(Exception):
def __init__(self, original, *args, **kwargs):
super(MyException, self).__init__(str(original), *args, **kwargs)
self.original = original
def raise_as(except_classes, target_class):
def wrapper(f):
@functools.wraps(f)
def wrapper_inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except except_classes as e:
raise target_class(e)
return wrapper_inner
return wrapper
@raise_as(IndexError, MyException)
def func(a):
l = [1,2]
return l[a]
The first is MyException and the second is TypeError.
func(3) # MyException
func('hoge') # TypeError
Fine control is impossible.
def try_return(except_classes, value=None):
def wrapper(f):
def wrapper_inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except except_classes:
return value
return wrapper_inner
return wrapper
@try_return(ZeroDivisionError, None)
def func(x):
return 1 / x
print func(1) # 1
print func(0) # None
Recommended Posts