重複の可能性:
when is it necessary to add anelse
clause to a try..except in Python?
Python try-elseは他の用途は何ですか:試した後に/ except節
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節の使用量は、どのようなものですし、実行されるのだろうか?
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
tryブロックに戻り値がある場合、elseも実行されません。 –
ここでtry-elseを使用すると便利なときは非常に良い説明があります:http://stackoverflow.com/a/855764/621591 –