10.1 Python中的異常
- NameError:嘗試訪問一個未申明的變量
- Zer0DivisionError:除數為零
- SyntaxError:Python解釋器語法錯誤
- IndexError:請求的索引超出序列范圍
- KeyError:請求一個不存在的字典關鍵字
- IOError:輸入/輸出錯誤
- Attribute:嘗試訪問位置的對象屬性
- ValueError:值錯誤
- TypeError:類型錯誤,通常指賦值左右兩邊類型不相同產生的錯誤
10.2 檢測和處理異常
10.2.1 try-except語句
try:
try_suite #監控這里的異常
except Exception1[, reason1]:
except_suite1 #異常處理代碼1
except Exception2[, reason1]:
except_suite1 #異常處理代碼2
except Exception3[, reason1]:
except_suite1 #異常處理代碼3
...
還可以將多個異常放于一個expect語句中:
try:
try_suite #監控這里的異常
except (Exception1, Exception2)[, reason1]:
except_suite #異常處理代碼
由于異常在Python 2.5中,被遷移到了新式類上,啟用了一個新的“所有異常之母”,這個類叫做BaseException,KeyboardInterrupt和SystemExit與Exception平級。
如果需要捕獲所有異常,那么可以這樣寫:
try:
try_suite #監控這里的異常
except BaseException, e:
except_suite #對所有異常的處理代碼
10.2.2 try-finally語句
try-finally與try-excpet區別在于它不是用來捕捉異常的,它常常用來維持一致的行為而無論異常是否發生。
try:
try_suite
finally:
finally_suite #無論如何都執行
舉個例子:當嘗試讀取一個文件的時候拋出異常,最終還是需要關閉文件,代碼可以這樣處理:
try:
try:
ccfile = open('carddata.txt','r')
txns = ccfile.readlines()
except IOError:
log.write('no txns this month\n')
finally:
ccfile.close()
10.2.3 try-except-else-finally語句總結
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2, Exception3, Exception4):
suite_for_Exception_2_3_and_4
except Exception5, Argument5:
suite_for_Exception5_plus_argument
except (Except6, Except7), Argument76:
suite_for_Exception6_and_7_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite