为什么下面的Python代码片段的输出不只是也不例外:1,因为第一次迭代过程中没有出现的异常.来自python docs(https://docs.python.org/2.7/tutorial/errors.html).
try ... except语句有一个可选的else子句,当存在时,必须遵循所有except子句.如果try子句不引发异常,则必须执行的代码很有用.
$ 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10078 次 |
| 最近记录: |