用于在发生异常时重试代码块的设计模式

2024-05-16 07:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找到一种设计模式——我确信有一种模式存在,这个问题很常见。你知道吗

在我的应用程序中,如果用户失去了Internet连接,我希望能够暂停应用程序,允许用户检查连接并重试。当一个连接成功时,应用程序就会离开它停止的地方。你知道吗

我试过这样做:

while True:
   try:
       for url in urls:
           downloadPage(url)
   except ConnectionException:
       raw_input('Connection lost. Press enter to try again')
       continue

但是这不起作用,因为如果在for循环中引发异常,它将捕获它,但是当它继续时,它将从urls列表的开头重新启动。你知道吗

我确实需要在应用程序开始运行之前和每次请求期间检查连接错误。这样我就可以暂停了。但我不想在所有代码中乱扔try/catch块。你知道吗

这有规律吗?你知道吗


Tags: 用户intrue应用程序urlfor地方模式
3条回答

这将尝试连接最多3次,然后删除当前url并转到下一个url。因此,如果无法建立连接,您不会陷入困境,但仍然有机会访问每个url。你知道吗

for url in urls:
    retries = 3
    while True:
        try:
            downloadPage(url)
        except ConnectionException:
            retries -= 1
            if retries == 0:
                print "Connection can't be established for url: {0}".format(url)
                break            
            raw_input('Connection lost. Press enter to try again')

您可以在for循环中移动try

for url in urls:
    while True:
        try:
            downloadPage(url)
        except ConnectionException:
            raw_input('Connection lost. Press enter to try again')

为什么不是这个?你知道吗

while True:
   for url in urls:
       success = False
       while (not success):
           try:
               downloadPage(url)
               success = True
           except ConnectionException:
               raw_input('Connection lost. Press enter to try again')

相关问题 更多 >