Python使用Try Exception來處理異常機制 若Exception中有Try對應(yīng)的異常處理,則Try - exception之后的代碼將被執(zhí)行,但若Try - exception中沒有對應(yīng)的代碼,則程序拋出Traceback停止運行 那么else finally就是針對這兩種情況帶來的后果分別相應(yīng)的關(guān)鍵字
else
如果一個Try - exception中,沒有發(fā)生異常,即exception沒有執(zhí)行,那么將會執(zhí)行else語句的內(nèi)容
反之,如果觸發(fā)了Try - exception(異常在exception中被定義),那么將會執(zhí)行exception中的內(nèi)容,而不執(zhí)行else中的內(nèi)容
下面代碼在python 3中運行通過
try: a = 1 / 0except ZeroDivisionError: print("Division is 0 ,Wrong!")else: print("Program is running here!")由于此時觸發(fā)了Try - exception,所以執(zhí)行exception
不執(zhí)行else
輸出結(jié)果:Division is 0 ,Wrong!
try: a = 1 / 1except ZeroDivisionError: print("Division is 0 ,Wrong!")else: print("Program is running here!")同理,這段代碼由于try中無異常,所以執(zhí)行else語句
輸出結(jié)果:Program is running here!
所以如果try中的異常在exception中被指出,那么:
Try - exception-else中,執(zhí)行了exception不執(zhí)行else,執(zhí)行else不執(zhí)行exception。
或者這么理解:
作者希望Try - exception是指出錯誤的,如果Try - exception并沒有指出錯誤,則是另外(else)的情況,所以執(zhí)行else語句
finally
如果try中的異常沒有在exception中被指出,那么系統(tǒng)將會拋出Traceback(默認(rèn)錯誤代碼),并且終止程序,接下來的所有代碼都不會被執(zhí)行,但如果有Finally關(guān)鍵字,則會在程序拋出Traceback之前(程序最后一口氣的時候),執(zhí)行finally中的語句。這個方法在某些必須要結(jié)束的操作中頗為有用,如釋放文件句柄,或釋放內(nèi)存空間等。
try: a = 1 / '1'except ZeroDivisionError: print("Division is 0 ,Wrong!")else: print("Program is running here!")這個程序會輸出Traceback
Traceback (most recent call last):
File “*********************, line 2, in
a = 1 / ‘1'
TypeError: unsupported operand type(s) for /: ‘int' and ‘str'
因為try中的異常沒有在exception中被指出,如果改為下面程序
try: a = 1 / '1'except ZeroDivisionError: print("Division is 0 ,Wrong!")finally: print("Program is running here!")輸出結(jié)果:
Traceback (most recent call last):
File “********************”, line 2, in
a = 1 / ‘1'
TypeError: unsupported operand type(s) for /: ‘int' and ‘str'
Program is running here!
可見,即使Traceback沒有消除,但依舊輸出了print語句,這就是相當(dāng)于一個程序的收尾工作(finally)
新聞熱點
疑難解答