python:try/except/else和continue语句

sat*_*esh 7 python python-2.7

为什么下面的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)

Tim*_*ers 5

本教程提供了一个良好的开端,但不是语言参考. 在这里阅读参考.

特别注意:

如果控制流出try子句的末尾,则执行可选的else子句.

脚注2澄清:

目前,除了异常或执行return,continue或break语句之外,控制"流出结束".

所以你continue明确地使用了它.