I have multiple functions calling which need to throw the same exceptions, i have created a decorator for this task so as to not repeat the exception handling code, but i would like to make this decorator generic so as to handle exceptions specified by user. I am attaching my sample code below.
def exception_decorator(func):
def new_func(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return ret
except OSError as e1:
return str(e1)
except ZeroDivisionError as e2:
return str(e2)
except ImportError as e3:
return str(e3)
except IOError as e4:
return str(e4)
except NameError as e5:
return str(e5)
return new_func
class Foo:
def __init__(self):
pass
@exception_decorator
def func1(self):
return 1/0
@exception_decorator
def func2(self):
f = open("filename","r")
return "done"
@exception_decorator
def func3(self):
return datetime.datetime.now()
obj = Foo()
print obj.func2()
I have hardcoded the list of exceptions in the decorator, i want the list of exceptions to be passed when applying the decorator and achieve the same behavior. Any ideas how this could be implemented. Also how do i make this decorator a class function instead of defining it outside the class? Thanks in advance for the help.