为什么python中的try语句需要else子句? [英] Why is else clause needed for try statement in python?
问题描述
在Python中,try语句支持一个else子句,如果try块中的代码不引发异常,它将执行。例如:
In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
为什么需要else子句?我们不能写上面的代码如下:
Why is the else clause needed? Can't we write the above code as follows :
try:
f = open('foo', 'r')
data = f.read()
f.close()
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
执行不会继续到 data = f。 read()
如果打开不引发异常?
Won't the execution proceed to data = f.read()
if open does not raise an exception?
推荐答案
区别是如果你在f.read()或f.close()代码中收到错误。在这种情况下:
The difference is what happens if you get an error in the f.read() or f.close() code. In this case:
try:
f = open('foo', 'r')
data = f.read()
f.close()
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
f.read()
或 f.close()
在这种情况下会给你日志消息无法打开foo
,这显然是错误的。
An error in f.read()
or f.close()
in this case would give you the log message "Unable to open foo"
, which is clearly wrong.
在这种情况下,这是避免的:
In this case, this is avoided:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
读取或关闭的错误不会导致日志写入,但是在调用堆栈中错误会上升。
And error in reading or closing would not cause a log write, but the error would rise uncatched upwards in the call stack.
这篇关于为什么python中的try语句需要else子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!