我正在寻找一种方法来恢复处理异常后的代码。具体来说,我遇到了一个问题,我试图点击不同的按钮,但有时会出现弹出窗口并中断该过程。我无法预测弹出窗口何时会发生,但无论何时出现,我都需要继续我离开的地方。我能想到编码的唯一方法就是这样:
try:
click_button_1()
except:
handle_pop_up()
click_button_1()
try:
click_button_2()
except:
handle_pop_up()
click_button_2()
try:
click_button_3()
except:
handle_pop_up()
click_button_3()
显然,这是一种非常不切实际的编码方式,因为每一行都必须在自己的try / except块中,但我似乎找不到更好的东西。
编辑:别担心,每个人,在我使用这个时会有特定的例外:)我只是用过,除非:为了简单起见。
答案 0 :(得分:1)
for func in [click_button_1,
click_button_2,
click_button_3]:
while True:
try:
func()
except: # you should really put a specific exception here
handle_pop_up()
else:
break
while
循环是为了确保即使问题多次发生也能正常运行。
答案 1 :(得分:1)
如果有几个函数必须处理相同类型的异常并以相同的方式处理它,我会写一个装饰器并装饰所有这些:
def with_exception_handling(func):
def handled_func(*a, **kw):
try:
func(*a, **kw)
except Exception:
handle_pop_up()
func(*a, **kw)
然后装饰每一个:
@with_exception_handling
def click_button_1():
...
@with_exception_handling
def click_button_2():
...
@with_exception_handling
def click_button_3():
...
稍后,只需使用它们:
click_button_1()
click_button_2()
click_button_3()
Sam 在评论中询问使用装饰器的解决方案,但处理多个异常(如Alex's answer中所述)。
很容易做到这两点:
def with_multiple_exception_handling(func):
def handled_func(*a, **kw):
while True:
try:
func(*a, **kw)
except Exception:
handle_pop_up()
else:
break
免责声明:当然,根据具体情况,这可能是也可能不需要。此外,我宁愿不抓住通用Exception
。而不是那样,应该以这种方式处理预期的特定异常。
答案 2 :(得分:0)
您可以使用重试装饰器。
from retrying import retry
def my_exception(exception):
#should really catch particular exceptions, implement the next
#if isinstance(exception,yourexceptiontype)
print "Saw an exception"
@retry(retry_on_exception=my_exception, hook=handle_pop_up)
def run():
click_button_1()
click_button_2() #and continue