python 捕获异常并继续尝试块 [英] python catch exception and continue try block

查看:29
本文介绍了python 捕获异常并继续尝试块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异常发生后可以返回执行try-block吗?(目标是少写)例如:

Can I return to executing try-block after exception occurs? (The goal is to write less) For Example:

try:
    do_smth1()
except:
    pass

try:
    do_smth2()
except:
    pass

对比

try:
    do_smth1()
    do_smth2()
except:
    ??? # magic word to proceed to do_smth2() if there was exception in do_smth1

推荐答案

不,你不能那样做.这就是 Python 的语法.一旦你因为异常退出了 try-block,就没有办法再进去了.

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

那么 for 循环呢?

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
    try:
        func()
    except Exception:
        pass  # or you could use 'continue'

但是请注意,只有 except 被认为是一种不好的做法.您应该改为捕获特定异常.我为 Exception 捕获,因为在不知道方法可能抛出什么异常的情况下,我可以做到这一点.

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

这篇关于python 捕获异常并继续尝试块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆