《Python核心編程》第10章錯(cuò)誤和異常學(xué)習(xí)筆記

10.1 Python中的異常

  1. NameError:嘗試訪問(wèn)一個(gè)未申明的變量
  2. Zer0DivisionError:除數(shù)為零
  3. SyntaxError:Python解釋器語(yǔ)法錯(cuò)誤
  4. IndexError:請(qǐng)求的索引超出序列范圍
  5. KeyError:請(qǐng)求一個(gè)不存在的字典關(guān)鍵字
  6. IOError:輸入/輸出錯(cuò)誤
  7. Attribute:嘗試訪問(wèn)位置的對(duì)象屬性
  8. ValueError:值錯(cuò)誤
  9. TypeError:類(lèi)型錯(cuò)誤,通常指賦值左右兩邊類(lèi)型不相同產(chǎn)生的錯(cuò)誤

10.2 檢測(cè)和處理異常

10.2.1 try-except語(yǔ)句

try:
    try_suite    #監(jiān)控這里的異常
except Exception1[, reason1]:
    except_suite1    #異常處理代碼1
except Exception2[, reason1]:
    except_suite1    #異常處理代碼2
except Exception3[, reason1]:
    except_suite1    #異常處理代碼3
...

還可以將多個(gè)異常放于一個(gè)expect語(yǔ)句中:

try:
    try_suite    #監(jiān)控這里的異常
except (Exception1, Exception2)[, reason1]:
    except_suite    #異常處理代碼

由于異常在Python 2.5中,被遷移到了新式類(lèi)上,啟用了一個(gè)新的“所有異常之母”,這個(gè)類(lèi)叫做BaseException,KeyboardInterrupt和SystemExit與Exception平級(jí)。

如果需要捕獲所有異常,那么可以這樣寫(xiě):

try:
    try_suite    #監(jiān)控這里的異常
except BaseException, e:
    except_suite    #對(duì)所有異常的處理代碼

10.2.2 try-finally語(yǔ)句

try-finally與try-excpet區(qū)別在于它不是用來(lái)捕捉異常的,它常常用來(lái)維持一致的行為而無(wú)論異常是否發(fā)生。

try:
   try_suite
finally:
    finally_suite  #無(wú)論如何都執(zhí)行

舉個(gè)例子:當(dāng)嘗試讀取一個(gè)文件的時(shí)候拋出異常,最終還是需要關(guān)閉文件,代碼可以這樣處理:

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語(yǔ)句總結(jié)

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容