python - 手动降低Python中的异常

标签 python python-2.7

有没有办法降低异常,以便在异常发生和程序退出之前执行 try 语句的其余部分?

while(True):
    try:
        do something 1
        error occurs here
        do something 2
    except error as e:
         if(iteration == 2):
             iteration += 1
             # here I want to go back to do something 2 instead of exit()
         exit()

最佳答案

The try statement :

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded:

def f():
    try:
        1/0
    finally:
        return 42

>>> f()
42

关于python - 手动降低Python中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31344816/

相关文章:

python - pygtk:如何在gtk.EntryCompletion中设置弹出窗口的高度

python - 为什么 python 需要 global 关键字而 C/C++ 不需要?

python - 如何将 Django 模块添加到 pydiction 字典?

python - 对创建的文本文件的数据进行排序

macos - 编写 .cargo/config.toml 以允许 rust 代码被 python 导入

python - 删除列表中其他字符串的子字符串而不更改列表的原始顺序?

python - 如何在使用nose2运行测试时静音.pyc文件生成

Python 关于舍入的奇怪行为

python - 是否可以使用 p7 python 发行版安装 SciPy?

Python TkMessageBox 问题不工作!