什么时候需要在Python中的try..except中添加一个“else”子句? [英] when is it necessary to add an `else` clause to a try..except in Python?
问题描述
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 You use the else
version if it makes the code more readable.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屋!