python catch exception and continue try block(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 捕获异常并继续尝试块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python 捕获异常并继续尝试块
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
