问题描述
try
语句的可选 else
子句的预期用途是什么?
What is the intended use of the optional else
clause of the try
statement?
推荐答案
else
块中的语句将执行,如果执行落在 try
- 如果没有例外。老实说,我从来没有需要。
The statements in the else
block are executed if execution falls off the bottom of the try
- if there was no exception. Honestly, I've never found a need.
然而,注意:
所以,如果你有一个方法可以,例如,抛出一个 IOError
,并且您想要捕获它引发的异常,但是如果第一个操作成功,还有其他一些要做的事情,并且您不想从该操作中捕获IOError,那么您可能会写这样做:
So, if you have a method that could, for example, throw an IOError
, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this:
try:
operation_that_can_throw_ioerror()
except IOError:
handle_the_exception_somehow()
else:
# we don't want to catch the IOError if it's raised
another_operation_that_can_throw_ioerror()
finally:
something_we_always_need_to_do()
如果您在 operation_that_can_throw_ioerror
之后放置 another_operation_that_can_throw_ioerror()
code>除将捕获第二个调用的错误。如果你把它放在整个 try
块之后,它总是运行,直到终于
。 else
可以确保
If you just put another_operation_that_can_throw_ioerror()
after operation_that_can_throw_ioerror
, the except
would catch the second call's errors. And if you put it after the whole try
block, it'll always be run, and not until after the finally
. The else
lets you make sure
- 第二个操作仅在没有异常的情况下运行
- 它在
最终
块之前运行,而 - 任何
IOError
它不会在这里被捕获
- the second operation's only run if there's no exception,
- it's run before the
finally
block, and - any
IOError
s it raises aren't caught here
这篇关于Python try-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!