我們把我們的主程序代碼包裹進(jìn)了try
從句。然后我們把一些代碼包裹進(jìn)一個(gè)except
從句,它會(huì)在try
從句中的代碼觸發(fā)異常時(shí)執(zhí)行。
在下面的例子中,我們還會(huì)使用第三個(gè)從句,那就是finally
從句。包裹到finally
從句中的代碼不管異常是否觸發(fā)都將會(huì)被執(zhí)行。這可以被用來(lái)在腳本執(zhí)行之后做清理工作。這里是個(gè)簡(jiǎn)單的例子:
try:
file = open('test.txt', 'rb')
except IOError as e:
print('An IOError occurred. {}'.format(e.args[-1]))
finally:
print("This would be printed whether or not an exception occurred!")
# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!