轉載:https://blog.csdn.net/watkinsong/article/details/27350553
try ... except ... else ... finally
def exceptTeset():
try:
print("doing some work, and maybe exception will be raised")
raise IndexError('Index error')
print("IndexError('Index error')")
#return 1
except KeyError:
print("in KeyError except")
#return 2
except IndexError:
print("in IndexError except")
#return 3
except ZeroDivisionError:
print("in ZeroDivisionError")
#return 4
else:
print("no exception")
#return 5
finally:
print("will be excuted anyway.")
#return 6
if __name__ == "__main__":
result = exceptTeset()
print(result)
【註解】:
- finally中代碼無論怎麼樣都會被執行,即時前面的語句中包含了return關鍵字。
- 在try中執行代碼,如果不發生異常,在執行else和finally中代碼,如果發生異常,則except捕獲對應異常,執行處理代碼和finally最終代碼;