在while循环中处理异常

2024-05-15 01:48:46 发布

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

我正在调用一个函数,该函数将在网页尚未加载时引发异常。我想等2秒钟,然后再试一次,直到页面加载完毕。

我试试这个:

while(True):
    try:
        some_funciont()
        break
    except:
        time.sleep(2)

但它在第一次迭代之后就消失了。

如果没有引发异常,如何逃逸?


Tags: 函数true网页timesleepsome页面try
3条回答

试试这样的:

def some_function(){
    try:
        #logic to load the page. If it is successful, it will not go to except.
        return True
    except:
        #will come to this clause when page will throw error.
        return False
    }

while(True)
    if some_function():
        break
    else:
        time.sleep(2)
        continue

为什么不这样做:

res = False
while (res == False):
    time.sleep(2)
    try:
        some_function()
        res = boolean(some_function())
    except:
        continue

try块中的所有内容都将被执行,直到引发一个Exception,这种情况下将调用except块。

所以你在第一次迭代中就崩溃了。

我想你的意思是:

while(True):
    try:
        some_function()
    except:
        time.sleep(2)
        break

当引发异常时,while循环将被中断。

相关问题 更多 >

    热门问题