【Python笔记】异常处理
1 什么是異常
異常即是一個(gè)事件,該事件會(huì)在程序執(zhí)行過程中發(fā)生,影響了程序的正常執(zhí)行。一般情況下,在Python無法正常處理程序時(shí)就會(huì)發(fā)生一個(gè)異常。異常是Python對象,表示一個(gè)錯(cuò)誤。
當(dāng)Python腳本發(fā)生異常時(shí)我們需要捕獲處理它,否則程序會(huì)終止執(zhí)行。
2 常見的異常的類型
Python中對于異常的分類:
| BaseException | 所有異常的基類 |
| SystemExit | 解釋器請求退出 |
| KeyboardInterrupt | 用戶中斷執(zhí)行(通常是輸入^C) |
| Exception | 常規(guī)錯(cuò)誤的基類 |
| StopIteration | 迭代器沒有更多的值 |
| GeneratorExit | 生成器(generator)發(fā)生異常來通知退出 |
| StandardError | 所有的內(nèi)建標(biāo)準(zhǔn)異常的基類 |
| ArithmeticError | 所有數(shù)值計(jì)算錯(cuò)誤的基類 |
| FloatingPointError | 浮點(diǎn)計(jì)算錯(cuò)誤 |
| OverflowError | 數(shù)值運(yùn)算超出最大限制 |
| ZeroDivisionError | 除(或取模)零 (所有數(shù)據(jù)類型) |
| AssertionError | 斷言語句失敗 |
| AttributeError | 對象沒有這個(gè)屬性 |
| EOFError | 沒有內(nèi)建輸入,到達(dá)EOF 標(biāo)記 |
| EnvironmentError | 操作系統(tǒng)錯(cuò)誤的基類 |
| IOError | 輸入/輸出操作失敗 |
| OSError | 操作系統(tǒng)錯(cuò)誤 |
| WindowsError | 系統(tǒng)調(diào)用失敗 |
| ImportError | 導(dǎo)入模塊/對象失敗 |
| LookupError | 無效數(shù)據(jù)查詢的基類 |
| IndexError | 序列中沒有此索引(index) |
| KeyError | 映射中沒有這個(gè)鍵 |
| MemoryError | 內(nèi)存溢出錯(cuò)誤(對于Python 解釋器不是致命的) |
| NameError | 未聲明/初始化對象 (沒有屬性) |
| UnboundLocalError | 訪問未初始化的本地變量 |
| ReferenceError | 弱引用(Weak reference)試圖訪問已經(jīng)垃圾回收了的對象 |
| RuntimeError | 一般的運(yùn)行時(shí)錯(cuò)誤 |
| NotImplementedError | 尚未實(shí)現(xiàn)的方法 |
| SyntaxError | Python 語法錯(cuò)誤 |
| IndentationError | 縮進(jìn)錯(cuò)誤 |
| TabError | Tab 和空格混用 |
| SystemError | 一般的解釋器系統(tǒng)錯(cuò)誤 |
| TypeError | 對類型無效的操作 |
| ValueError | 傳入無效的參數(shù) |
| UnicodeError | Unicode 相關(guān)的錯(cuò)誤 |
| UnicodeDecodeError | Unicode 解碼時(shí)的錯(cuò)誤 |
| UnicodeEncodeError | Unicode 編碼時(shí)錯(cuò)誤 |
| UnicodeTranslateError | Unicode 轉(zhuǎn)換時(shí)錯(cuò)誤 |
| Warning | 警告的基類 |
| DeprecationWarning | 關(guān)于被棄用的特征的警告 |
| FutureWarning | 關(guān)于構(gòu)造將來語義會(huì)有改變的警告 |
| OverflowWarning | 舊的關(guān)于自動(dòng)提升為長整型(long)的警告 |
| PendingDeprecationWarning | 關(guān)于特性將會(huì)被廢棄的警告 |
| RuntimeWarning | 可疑的運(yùn)行時(shí)行為(runtime behavior)的警告 |
| SyntaxWarning | 可疑的語法的警告 |
| UserWarning | 用戶代碼生成的警告 |
3 異常處理的實(shí)例
異常處理的通用結(jié)構(gòu):
try:#可能出現(xiàn)異常的代碼 code except 異常名:code else:#未發(fā)生異常時(shí),執(zhí)行這里的語句#else也可以不寫 your code #other code of your program code當(dāng)我們不清楚異常的具體類型的時(shí)候,我們可以獲取異常的參數(shù):
try:You do your operations here;...................... except ExceptionType, Argument:You can print value of Argument here...try-finally的使用,try-finally 語句無論是否發(fā)生異常都將執(zhí)行最后的代碼。
注意:你可以使用except語句或者finally語句,但是兩者不能同時(shí)使用。else語句也不能與finally語句同時(shí)使用
在平常寫程序的過程中,容易用到的場景包括文件的讀寫操作和數(shù)據(jù)庫的相關(guān)操作,下面來舉幾個(gè)例子說明如何編寫異常處理的代碼。
#coding=utf-8 # this is an example for file io exception processing # open a file import os#獲取當(dāng)前文件的路徑 file_path = os.getcwd() print file_path file_name = "data.txt" #反斜杠要加轉(zhuǎn)義字符 file_name = file_path + '\\' + file_name print file_name #以各種權(quán)限打開文件 ''' w 以寫方式打開, a 以追加模式打開 (從 EOF 開始, 必要時(shí)創(chuàng)建新文件) r+ 以讀寫模式打開 w+ 以讀寫模式打開 (參見 w ) a+ 以讀寫模式打開 (參見 a ) rb 以二進(jìn)制讀模式打開 wb 以二進(jìn)制寫模式打開 (參見 w ) ab 以二進(jìn)制追加模式打開 (參見 a ) rb+ 以二進(jìn)制讀寫模式打開 (參見 r+ ) wb+ 以二進(jìn)制讀寫模式打開 (參見 w+ ) ab+ 以二進(jìn)制讀寫模式打開 (參見 a+ ) ''' #myfile = file(file_name , 'w') #異常處理myfile = file(file_name )#讀取文件中的內(nèi)容 one_line_content = myfile.readline() #讀取一行的信息print myfile.tell() content = myfile.read() #讀取當(dāng)前位置之后的所有的信息 print content print "read one line" print myfile.tell() print one_line_contenttry:myfile.read() except Exception,e:print "error happened ", e else:print "there is no exception" print "go on with the program" print "do something else!"#讀取完文件之后要關(guān)閉文件 myfile.close() try:myfile.read() except IOError: # 根據(jù)異常的種類進(jìn)行捕獲操作print "this is a io error" except NameError:print "this is a name error" except ValueError:print "this is a value error" else: #如果try代碼中沒有發(fā)生異常會(huì)執(zhí)行else里邊的操作print "other kind of error" print "go on with the progarmme"對應(yīng)的數(shù)據(jù)文件:data.txt
name:12341 zhaozilong:456 zhaoyun:134 simayi:33 Jack:23 Rose:55
?
參考文章和連接
①Python異常處理 ?W3C
轉(zhuǎn)載于:https://www.cnblogs.com/codemyzen/p/4228132.html
總結(jié)
以上是生活随笔為你收集整理的【Python笔记】异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 摩托罗拉:未来一切以手机为中心
- 下一篇: python安装win32com模块