在此鏈接(https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions):終於在Python增加只是下面是說更好的可讀性
一個finally從句離開try語句,是否已經發生異常之前始終執行。
CODE 1:
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 1:
Performing an action which may throw an exception.
Everything looks great!
Finally is called directly after executing the try statement whether an exception is thrown or not.
CODE 2:
try:
print "Performing an action which may throw an exception."
raise Exception('spam', 'eggs') # This is new
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 2:
Performing an action which may throw an exception.
An exception was thrown!
('spam', 'eggs')
Finally is called directly after executing the try statement whether an exception is thrown or not.
我從中得到的結果是else
只有在沒有異常時纔會執行。
問題:
只是用於更好的可讀性finally
?
因爲我可以在嘗試後放這個打印語句,就像在這段代碼中一樣。
代碼3:
try:
print "Performing an action which may throw an exception."
#raise Exception('spam', 'eggs') # with this line or without last print is done
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
如果任何代碼*在函數中返回*,或者在循環中使用'continue'或'break',則不會執行print語句。 – 2014-10-09 16:08:13
是不是最後的聲明有清理的目的?此外,[在java中是不是一樣?](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html]) – JoErNanO 2014-10-09 16:09:36