[英]Exception handling in python for multiple functions
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.
先谢谢您的帮助。
You can use a wrapper function that takes variable arguments of exceptions and returns a decorator: 您可以使用包装函数,该函数接受异常的变量参数并返回装饰器:
def exception_decorator(*exceptions):
def decorator(func):
def new_func(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return ret
except exceptions as e:
return str(e)
return new_func
return decorator
so that: 以便:
import datetime
class Foo:
def __init__(self):
pass
@exception_decorator(ZeroDivisionError)
def func1(self):
return 1/0
@exception_decorator(IOError, OSError)
def func2(self):
f = open("filename","r")
return "done"
@exception_decorator(TypeError, ValueError)
def func3(self):
return datetime.datetime.strptime('2018/13/06', '%Y/%m/%d')
obj = Foo()
print obj.func1()
print obj.func2()
print obj.func3()
outputs: 输出:
integer division or modulo by zero
[Errno 2] No such file or directory: 'filename'
time data '2018/13/06' does not match format '%Y/%m/%d'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.