为什么下面的python代码片段的输出不是只是没有异常:1,因为在第一次迭代期间没有引发异常。来自python文档(https://docs.python.org/2.7/tutorial/errors.html)。
The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
$ cat hello.py
for x in range(1,10):
try:
if x == 1:
continue
x/0
except Exception:
print "Kaput:%s" %(x)
else:
print "No exception:%s" %(x)
break
$ python hello.py
Kaput:2
Kaput:3
Kaput:4
Kaput:5
Kaput:6
Kaput:7
Kaput:8
Kaput:9
$ python -V
Python 2.7.8
您的代码有一个
continue
,因此它永远不会到达else
块。要实现您的结果,您不能到达continue
:代码:
结果:
这与你使用
continue
和break
有关。我想这就是你想要的功能。基本上,continue
不会跳到else
语句,而是继续执行代码(通过try语句)。并且,break
中断for循环,因此不会产生更多输出,所以我删除了该语句。本教程提供了一个良好的开始,但不是语言参考。Read the reference here.
特别注意:
脚注2澄清:
所以你对
continue
的使用是由它显式地解决的。相关问题 更多 >
编程相关推荐