简体   繁体   中英

python: try/except/else and continue statement

Why is the output of the below python code snippet NOT just No exception:1 , since during first iteration there is no exception raised. From python docs ( 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

The tutorial gives a good start, but is not the language reference. Read the reference here.

Note in particular:

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

clarified by footnote 2:

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

So your use of continue is explicitly addressed by that.

Your code has a continue , so it never gets to the else block. To achieve your result, you can not get to the continue :

Code:

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

Result:

No exception:1

It has to do with your use of continue and break . I think this is the functionality you're going for. Basically, continue does not skip to the else statement, it continues on with the code (passed the try statement). And, break breaks the for loop, thus producing no more output, so I removed that statement.

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

这是因为continue语句...它将控制转换为语句..尝试删除continue并为x / 0添加条件语句,如if(x!= 1):x / 0然后看到输出你欲望..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM