What is the usage of else: after a try/except clause [duplicate]
Possible Duplicates:
when is it necessary to add anelse
clause to a try..except in Python? Python try-else
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()
What is usage of this else clause, and wh开发者_StackOverflow中文版en will it be executed?
The try...except...else statement mean something like this :
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
From the Python documentation:
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.
So the else
clause is executed when the try
does not not raise an exception and does not exit the block via control flow statement.
精彩评论