[英]Simplify try-except blocks in Python
我有很多模块。 它们在每个文件中都有类似的try-except块,如下所示:
from shared.Exceptions import ArgException # and others, as needed
try:
do_the_main_app_here()
except ArgException as e:
Response.result = {
'status': 'error',
'message': str(e)
}
Response.exitcode('USAGE')
# more blocks like the above
ArgException(和其他异常)定义为:
from abc import ABCMeta, abstractmethod
class ETrait(Exception):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ArgException(ETrait): pass
由于每个模块都使用类似的代码来捕获异常,是否有办法将异常捕获放入所有模块都使用的共享文件中?
我不会这样做,但是您可以在类似以下的模块中创建一个函数:
from shared.Exceptions import ArgException # and others, as needed
def try_exec(execution_function)
try:
execution_function()
except ArgException as e:
Response.result = {
'status': 'error',
'message': str(e)
}
Response.exitcode('USAGE')
然后在需要尝试捕获指令块时传递try_exec(do_the_main_app_here)
,并传递需要具有正确上下文的参数。
答案是肯定的,您可以创建一个模块来做到这一点。
最简单的方法是创建一个接受两个参数的函数:另一个函数是您要“尝试”的代码,以及在发生异常的情况下要执行的“操作”。
然后:
def myModuleFunction(tryThisCode, doThis):
try:
returnValue = tryThisCode()
return returnValue
except ArgException as e:
if (doThis == "doThat"):
...
else:
...
然后,在导入新模块之后,您可以使用如下功能:
myModuleFunction(divideByZero, 'printMe')
假设您有一个名为divideByZero()的函数;
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.