python:try/except/else和continue政治家

2024-05-21 04:43:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 代码文档pyanhelloforifexception
3条回答

您的代码有一个continue,因此它永远不会到达else块。要实现您的结果,您不能到达continue

代码:

for x in range(1, 10):
    try:
        if x != 1:
            x / 0
    except Exception:
        print "Kaput:%s" % (x)
    else:
        print "No exception:%s" % (x)
        break

结果:

No exception:1

这与你使用continuebreak有关。我想这就是你想要的功能。基本上,continue不会跳到else语句,而是继续执行代码(通过try语句)。并且,break中断for循环,因此不会产生更多输出,所以我删除了该语句。

for x in range(1,10):
  try:
    if x != 1:
        x/0
  except Exception:
    print "Kaput:%s" %(x)
  else:
    print "No exception:%s" %(x)

本教程提供了一个良好的开始,但不是语言参考。Read the reference here.

特别注意:

The optional else clause is executed if and when control flows off the end of the try clause.

脚注2澄清:

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

所以你对continue的使用是由它显式地解决的。

相关问题 更多 >