什么时候需要在Python中的try..except中添加一个“else”子句? [英] when is it necessary to add an `else` clause to a try..except in Python?

查看:271
本文介绍了什么时候需要在Python中的try..except中添加一个“else”子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pre $ try:
some_code_that_can_cause_an_exception( )
除了:
some_code_to_handle_exceptions()
else:
code_that_needs_to_run_when_there_are_no_exceptions()

如何不同于:

  try:
some_code_that_can_cause_an_exception()
except :
some_code_to_handle_exceptions()

code_that_needs_to_run_when_there_are_no_exceptions()

当没有例外时, code_that_needs_to_run_when_there_are_no_exceptions()将执行。有什么区别?

解决方案

实际上,在第二个片段中,最后一行总是执行。



您可能意味着

  try:
some_code_that_can_cause_an_exception()
code_that_needs_to_run_when_there_are_no_exceptions()
除了:
some_code_to_handle_exceptions()

我相信你可以使用 else 版本,如果它使代码更可读。如果你不使用 else 不想从 code_that_needs_to_run_when_there_are_no_exceptions 中捕获例外。


When I write code in Python with exception handling I can write code like:

try:
    some_code_that_can_cause_an_exception()
except:
    some_code_to_handle_exceptions()
else:
    code_that_needs_to_run_when_there_are_no_exceptions()

How does this differ from:

try:
    some_code_that_can_cause_an_exception()
except:
    some_code_to_handle_exceptions()

code_that_needs_to_run_when_there_are_no_exceptions()

In both cases code_that_needs_to_run_when_there_are_no_exceptions() will execute when there are no exceptions. What's the difference?

解决方案

Actually, in the second snippet, the last line executes always.

You probably meant

try:
    some_code_that_can_cause_an_exception()
    code_that_needs_to_run_when_there_are_no_exceptions()
except:
    some_code_to_handle_exceptions()

I believe you can use the else version if it makes the code more readable. You use the else variant if you don't want to catch exceptions from code_that_needs_to_run_when_there_are_no_exceptions.

这篇关于什么时候需要在Python中的try..except中添加一个“else”子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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