首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python异常处理中的Else子句应用程序

python异常处理中的Else子句应用程序
EN

Stack Overflow用户
提问于 2019-06-10 03:15:03
回答 3查看 89关注 0票数 2

为了处理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 和之间的区别是什么,哪个更可取,更有原则?

EN

回答 3

Stack Overflow用户

发布于 2019-06-10 03:18:04

else块将在finally块之前执行,“代码的其余部分”块将在finally块之后执行。

如果你没有finally代码块,那就没有什么区别了,我怀疑完全删除else代码块会使代码更整洁、更具可读性。

票数 2
EN

Stack Overflow用户

发布于 2019-06-10 03:18:16

只有在没有例外的情况下,# do something for else才会做一些事情。

# rest of codes总是会做一些事情。否则,这是一个操作的顺序。

票数 1
EN

Stack Overflow用户

发布于 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独立运行的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56517658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档