为了处理python中的异常,我们使用以下模式:
try:
# do something
except NameError:
# Do something for NameError exceptions
except:
# Do something for other exceptions
raise
else:
# Do something when didn't exist any exception
finally:
# Do something whether an exception has occurred or not
#rest of codes
我的问题是:
# rest of codes
和之间的区别是什么,哪个更可取,更有原则?
发布于 2019-06-10 03:18:04
else
块将在finally
块之前执行,“代码的其余部分”块将在finally
块之后执行。
如果你没有finally
代码块,那就没有什么区别了,我怀疑完全删除else
代码块会使代码更整洁、更具可读性。
发布于 2019-06-10 03:18:16
只有在没有例外的情况下,# do something for else
才会做一些事情。
而# rest of codes
总是会做一些事情。否则,这是一个操作的顺序。
发布于 2019-06-10 03:24:09
我试着用例子来演示,所以我稍微修改了你的代码,只关注相关的部分。
lst = [123, 512, 251]
for i in range(6):
try:
print(lst[i])
except IndexError:
print(f"Index {i} not there")
else:
print("HELLO")
finally:
pass
print("WORLD")
这是输出:
123
HELLO
WORLD
512
HELLO
WORLD
251
HELLO
WORLD
Index 3 not there
WORLD
Index 4 not there
WORLD
Index 5 not there
WORLD
因此,正如您所看到的,当try
块中的代码成功运行时,else
块中的代码也将运行。但代码是#rest of the codes
独立运行的。
https://stackoverflow.com/questions/56517658
复制相似问题