要添加到上面的其他答案,finally
子句無論如何執行,而else
子句只有在未引發異常時纔會執行。
例如,沒有例外寫入文件將輸出如下:
file = open('test.txt', 'w')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
OUTPUT:
Writing to file.
Write successful.
File closed.
如果出現異常,代碼將輸出以下內容(請注意,故意的錯誤是由保留文件引起的廣告只。
file = open('test.txt', 'r')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
OUTPUT:
Could not write to file.
File closed.
我們可以看到,無論例外的是,finally
條款執行。希望這可以幫助。
嘗試: #X =你好+ 20 X = 10 + 20 情況除外: 打印 '我除了塊' X = 20 + 30 其他: 打印 '我在別的塊' X + = 1 finally: print'Finally x =%s'%(x) – 2017-10-02 06:32:18