关于python:else的用法是什么:在try / except子句之后

What is the usage of else: after a try/except clause

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicates:
when is it necessary to add an else clause to a try..except in Python?
Python try-else

1
2
3
4
5
6
7
8
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

这个else子句的用法是什么,什么时候执行?


从python文档中:

The optional else clause is executed if and when control flows off the end of the try clause.7.2 Exceptions in the else clause are not handled by the preceding except clauses.

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

因此,当try不引发异常,也不通过控制流语句退出块时,执行else子句。


Try…Except…Else语句的含义如下:

1
2
3
4
5
6
try:
    # execute some code
except:
    # if code raises an error, execute this code
else:
    # if the"try" code did not raise an error, execute this code