问题
Possible Duplicate:
Python try-else
Comming from a Java background, I don't quite get what the else
clause is good for.
According to the docs
It is useful for code that must be executed if the try clause does not raise an exception.
But why not put the code after the try block? It seems im missing something important here...
回答1:
The else
clause is useful specifically because you then know that the code in the try
suite was successful. For instance:
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()
You can perform operations on f
safely, because you know that its assignment succeeded. If the code was simply after the try ... except, you may not have an f
.
回答2:
Consider
try:
a = 1/0
except ZeroDivisionError:
print "Division by zero not allowed."
else:
print "In this universe, division by zero is allowed."
What would happen if you put the second print
outside of the try/except/else
block?
回答3:
It is for code you want to execute only when no exception was raised.
来源:https://stackoverflow.com/questions/3996329/else-clause-in-try-statement-what-is-it-good-for