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 捕获异常并继续尝试块


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01