標籤:
本文和大家分享的主要是python中常見的錯誤與異常及其相關處理方式,一起來看看吧,希望對大家學習python有所協助。 1. 錯誤和異常的處理方式 1.常見的錯誤 1. a:NameError 2. if True:SyntaxError 3. f = oepn(’1.txt’):IOError 4. 10/0:ZeroDivisionError 5. a = int(’d’):ValueError 6. 程式運行中斷:KeyboardInterrupt 2.Python-使用try_except處理異常(1) try: try_suiteexcept Exception [e]: exception_block 1. try用來捕獲try_suite中的錯誤,並且將錯誤交給except處理 2. except用來處理異常,如果處理異常和設定捕獲異常一致,使用exception_block處理異常 # case 1try: undefexcept: print ’catch an except’ # case 2try: if undefexcept: print ’catch an except’ · case1:可以捕獲異常,因為是執行階段錯誤 · case2:不能捕獲異常,因為是語法錯誤,運行前錯誤 -- # case 3try: undefexcept NameError,e: print ’catch an except’,e # case 4try: undefexcept IOError,e: print ’catch an except’,e · case3:可以捕獲異常,因為設定捕獲NameError異常 · case4:不能捕獲異常,因為設定IOError,不會處理NameError Example import random num = random.randint(0, 100) while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print ’\n’ 3. Python使用try_except處理異常(2) · try-except:處理多個異常 try: try_suiteexcept Exception1[e]: exception_block1except Exception2[e]: exception_block2except ExceptionN[e]: exception_blockN 4. Python-try_finally使用 try: try_suitefinally: do_finally · 如果try語句沒有捕獲錯誤,代碼執行do_finally語句 · 如果try語句捕獲錯誤,程式首先執行do_finally語句,然後將捕獲的錯誤交給python解譯器處理 5. Python-try-except-else-finally try: try_suite except: do_except finally: do_finally · 若try語句沒有捕獲異常,執行完try程式碼片段後,執行finally · 若try捕獲異常,首先執行except處理錯誤,然後執行finally 6. Python-with_as語句 with context [as var]: with_suite · with語句用來代替try_except_finall語句,使代碼更加簡潔 · context運算式返回是一個對象 · var用來儲存context返回對象,單個傳回值或者元祖 · with_suite使用var變數來對context返回對象進行操作 with語句實質是上下文管理: 1. 上下文管理協議:包含方法 __enter__() 和 __exit()__ ,支援該協議的對象要實現這兩個方法 2. 上下文管理器:定義執行with語句時要建立的運行時上下文,負責執行with語句塊上下文中的進入與退出操作 3. 進入上下文管理器:調用管理器 __enter__ 方法,如果設定as var語句,var變數接受 __enter__() 方法傳回值 4. 退出上下文管理器:調用管理器 __exit__ 方法 class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_val if __name__ == "__main__": with Mycontex(’test context’) as f: print f.name f.do_self() whith語句應用情境: 1. 檔案操作 2. 進程線程之間互斥對象,例如互斥鎖 3. 支援內容相關的其他對象 2. 標準異常和自動以異常 1. Python-assert和raise語句 · rais語句 · reise語句用於主動拋出異常 · 文法格式:raise[exception[,args]] · exception:異常類 · args:描述異常資訊的元組 raise TypeError, ’Test Error’ raise IOError, ’File Not Exit’ · assert語句 · Assert 陳述式:assert語句用於檢測運算式是否為真,如果為假,引發AssertionError錯誤 · 文法格式:assert expression[,args] · experession:運算式 · args:判斷條件的描述資訊 assert 0, ’test assert’ assert 4==5, ’test assert’ 2. Python-標準異常和自訂異常 · 標準異常 · python內建異常,程式執行前就已經存在 · · 自訂異常: · python允許自訂異常,用於描述python中沒有涉及的異常情況 · 自訂異常必須繼承Exception類 · 自訂異常只能主動觸發 class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return ’CustionError:%s’ % self.message try: raise CustomError(’test CustomError’)except CustomError, e: print ’ErrorInfo:%d,%s’ % (id(e), e)來源:部落格園
Python錯誤和異常概念