【问题标题】:try except block not executing (but finally does)尝试除块不执行(但最终执行)
【发布时间】:2019-07-29 22:34:00
【问题描述】:

我的 python 脚本(单线程)运行了好几个小时,但是,过了一段时间它突然停止了。我们使用try-except 块来调试错误。但是,这表现得很奇怪。我们使用:

try:
    while True:
        # do routine
        time.sleep(someSeconds)
except Exception as e:
    # exception!
finally:
    # finish

while 例程正常执行,然后脚本(又名主线程)进入休眠状态,唤醒并再次执行例程。几小时后,finally 块被执行,没有异常块被执行(首先)。

这怎么可能? As far as I know,当 while True 循环因任何原因停止时,应该执行 except 块(在 finally 之前)?怎么会没有抓到错误呢?

注意:while循环中没有return/break

【问题讨论】:

    标签: python-3.x exception try-catch


    【解决方案1】:

    我能想到的两个选项:

    • 您的“例程”使用returnbreak 退出循环。

    • 引发了一个不是从Exception 派生的异常(添加except: print(“other exception”) 来测试)

    【讨论】:

    • 对于 Sexton 选项:如何获取其他异常的名称?在链接的答案中,该人说“except Exception”应该捕获每个异常。而且我认为任何异常都继承自 Exception?
    • 并非所有异常都派生自异常。例如,KeyboardInterrupt 派生自 BaseException。我发现了这个示例如何获取except: 子句中捕获的异常:print("Unexpected error:", sys.exc_info()[0])
    猜你喜欢
    • 2013-08-10
    • 2013-11-04
    • 2012-08-26
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多