Python基础(10) - 异常
Python
異常:程序出現了錯誤而在正常控制流以外采取的行為
Python中常見的異常:
1. NameError:嘗試訪問一個未聲明的變量
>>> something Traceback (most recent call last):File "<stdin>", line 1, in <module> NameError: name 'something' is not defined?
2. SyntaxError:解釋器語法錯誤,是唯一不在運行時發生的異常
>>> forFile "<stdin>", line 1for^ SyntaxError: invalid syntax?
3. IndexError:超出范圍的值索引序列
>>> lst = [] >>> lst[1] Traceback (most recent call last):File "<stdin>", line 1, in <module> IndexError: list index out of range try-except定義了進行異常監控的一段代碼,并提供了處理異常的機制
try:
?? try_suite #監控異常
except Exception[,reason]:
??? except_suite #異常處理代碼
>>> try: ... f = open('somefile','r') ... except IOError,e: ... print 'could not open file:',e ... could not open file: [Errno 2] No such file or directory: 'somefile' >>>上例中,只捕獲了IOError異常,任何其它異常不會被捕獲。
可以檢測多種異常:
try:
?? try_suite #監控這里的異常
except Exception1[,reason1]:
??? except_suite1 #異常處理代碼
except Exception2[,reason2]:
??? except_suite2 #異常處理代碼
>>> def safe_float(obj): ... try: ... retval = float(obj) ... except ValueError: ... retval = 'could not convert non-number to float' ... except TypeError: ... retval = 'object type cannot be converted to float' ... return retval ... >>> safe_float('xy.z') 'could not convert non-number to float' >>> safe_float([1,2]) 'object type cannot be converted to float' >>>一個except語句可以檢測多種異常,多個異常要放在一個元組中:
try:
?? try_suite #監控這里的異常
except (Exception1 [,Exception2 [, …ExceptionN]]) [,reason]:
??? except_suite #異常處理代碼
>>> def safe_float(obj): ... try: ... retval = float(obj) ... except (ValueError,TypeError): ... retval = 'could not convert to float' ... return retval ... >>> safe_float('xy.z') 'could not convert to float' >>> safe_float([1,2]) 'could not convert to float'一個except語句可以檢測多種異常,多個異常要放在一個元組中:
try:
?? try_suite #監控這里的異常
except Exception,e:
??? except_suite #異常處理代碼
?
Exception是大部分異常類的基類,因此上述代碼支持捕獲大多異常。KeyboardInterrupt(用戶中斷執行Ctrl+C)和SystemExit(python解釋器請求退出)不是由于代碼錯誤條件引起的異常,如下為異常類的樹:
-BaseException? |- KeyboardInterrupt
? |- SystemExit
? |- Exception
???? |-所有內建異常
?
try-except的作用是提供一個可以提示錯誤或處理錯誤的機制,而不是一個錯誤過濾器,下面這種捕獲所有異常并忽略錯誤不是一種合理的編程方式:
try:
??? …
except: Exception:
?? pass
?
避免把大片代碼裝入try-except中然后使用pass忽略掉錯誤。
可以捕獲特定的異常并忽略它們,或是捕獲所有的異常并采取特定的動作。
v異常參數:異常也可以有參數,標準內建異常提供至少一個參數,指示異常原因的一個字符串
異常參數自身會組成一個元組,并存儲為異常類的實例。
對于大多數內建異常,也就是從StandardError派生的異常,這個元組中只包含一個指示錯誤原因的字符串。操作系統或其他環境類型的錯誤,例如:IOError,元組中會把操作系統的錯誤編號放到錯誤字符串的前面
?
>>> try: ... float('xyz') ... except Exception,e: ... pass ... >>> e ValueError('could not convert string to float: xyz',) >>> type(e) <type 'exceptions.ValueError'> >>> isinstance(e, ValueError) True >>> isinstance(e, Exception) True vtry-finallytry:
??? try-suite
finally:
??? finally-suite #無論如何都執行
finally子句是無論異常是否發生,是否捕獲都會執行的一段代碼
當在try范圍中產生一個異常時,會立即跳轉到finally語句段,當finally中的所有代碼都執行完畢后,會繼續向上一層引發異常。
如果finally中的代碼引發了另一個異常或由于return、break、continue語法而終止,原來的異常將丟失而且無法重新引發。
try-except-else-finally
在try語句塊中所有代碼都執行成功后,將會執行else子句。
try:
??? try_suite
except Exception1:
??? suite_for_exception1
except (Exception2,Exception3,Exception4):
??? suite_for_exception2_and_3_and_4
except (Exception6, Exception7), Argument67:
??? suite_for_Exception6_and_7_plus_argument
except:
??? suite_for_all_other_exceptions
finally:
??? always_execute_suite
無論你選擇哪一種語法,至少要有一個except子句
?
try語句塊中異常發生點后的剩余語句將被忽略,不會被執行,解釋器將搜索處理器,一旦找到,就開始執行處理器中的代碼。如果沒有找到合適的處理器,那么異常就向上移交給調用者去處理,如果上層調用者也沒有找到合適的處理器,則該異常會繼續被向上移交,直到找到合適的處理器,如果到達最頂層仍然沒有找到對應處理器,那么就認為該異常未處理,解釋器會顯示出跟蹤記錄,然后退出。
?
之前看到的異常都是由解釋器觸發的。程序員也可以在遇到錯誤時主動觸發異常:
raise [SomeException, [args [, traceback]]]
SomeException:可以是異常類或實例,如果是一個實例,則不能再帶args參數
args: 異常參數
traceback: 跟蹤記錄對象
>>> class MyException(Exception): ... def __init__(self, length, atleast): ... Exception.__init__(self) ... self.length = length ... self.atleast = atleast ... def __str__(self): ... return 'MyException occered, length:%s, atleast:%s'%(self.length,self.atleast) ... >>> try: ... raise MyException(2,3) ... except MyException,e: ... print e ... MyException occered, length:2, atleast:3sys模塊中的exc_info()函數,是另一種獲取異常信息的途徑,它提供了一個三元祖信息,比我們單純用異常參數獲取的信息多
>>> exc_tuple (<type 'exceptions.ValueError'>, ValueError('could not convert string to float: xy.z',), <traceback object at 0x01C0DF08>)?
從sys.exc_info()得到的元組為:
exc_type: 異常類
exc_value:異常類的實例
exc_traceback: 跟蹤記錄對象
?
?
斷言是一句等價于布爾真的判定,如果表達式為假,觸發AssertionError異常
assert expression[, arguments]
>>> assert 1==1 >>> assert 1==0 Traceback (most recent call last):File "<stdin>", line 1, in <module> AssertionError >>> assert 1==0, 'one does not equal zero' Traceback (most recent call last):File "<stdin>", line 1, in <module> AssertionError: one does not equal zero用try-except可以捕獲AssertionError異常:
>>> try: ... assert 1==0 , 'one does not equal zero' ... except AssertionError,e: ... print '%s:%s'%(e.__class__.__name__,e) ... AssertionError:one does not equal zero >>>?
?
?
轉載于:https://www.cnblogs.com/TonyZhao/p/3530944.html
總結
以上是生活随笔為你收集整理的Python基础(10) - 异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: V4L2学习 二 ----视频打开与保存
- 下一篇: POI的一些配置