可能觸發(fā)異常產(chǎn)生的代碼會(huì)放到try語句塊里,而處理異常的代碼會(huì)在except語句塊里實(shí)現(xiàn)。例如:
try: file = open(‘test.txt’, ‘rb’)except IOError as e: print(‘An IOError occurred. {}’.format(e.args[-1]))
我們可以使用三種方法來處理多個(gè)異常。
第一種方法需要把所有可能發(fā)生的異常放到一個(gè)元組里。像這樣:
try: file = open(‘test.txt’, ‘rb’)except (IOError, EOFError) as e: print(“An error occurred. {}”.format(e.args[-1]))
另外一種方式是對每個(gè)單獨(dú)的異常在單獨(dú)的except語句塊中處理。我們想要多少個(gè)except語句塊都可以:
try: file = open(‘test.txt’, ‘rb’)except EOFError as e: print(“An EOF error occurred.”) raise eexcept IOError as e: print(“An error occurred.”) raise e
最后一種方式會(huì)捕獲所有異常:
try: file = open(‘test.txt’, ‘rb’)except Exception as e: # Some logging if you want raise e
注意,捕獲所有異常可能會(huì)造成意外的結(jié)果,比如,通常我們使用CTRL+C來終止程序,但如果程序中捕獲了所有異常,CTRL+C就無法終止程序了。
包裹到finally從句中的代碼不管異常是否觸發(fā)都將會(huì)被執(zhí)行。這可以被用來在腳本執(zhí)行之后做清理工作:
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!
如果想在沒有觸發(fā)異常的時(shí)候執(zhí)行一些代碼,可以使用else從句。
有人也許問了:如果你只是想讓一些代碼在沒有觸發(fā)異常的情況下執(zhí)行,為啥你不直接把代碼放在try里面呢?回答是,那樣的話這段代碼中的任意異常都還是會(huì)被try捕獲,而你并不一定想要那樣。
try: print(‘I am sure no exception is going to occur!’)except Exception: print(‘exception’)else: # any code that should only run if no exception occurs in the try, # but for which exceptions should NOT be caught print(‘This would only run if no exception occurs. And an error here ‘ ‘would NOT be caught.’)finally: print(‘This would be printed in every case.’)# Output: I am sure no exception is going to occur!# This would only run if no exception occurs. And an error here would NOT be caught# This would be printed in every case.
else從句只會(huì)在沒有異常的情況下執(zhí)行,而且它會(huì)在finally語句之前執(zhí)行。