日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python基础(10) - 异常

發(fā)布時間:2024/1/17 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础(10) - 异常 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python

異常:程序出現(xiàn)了錯誤而在正常控制流以外采取的行為

Python中常見的異常:

1. NameError:嘗試訪問一個未聲明的變量

>>> something Traceback (most recent call last):File "<stdin>", line 1, in <module> NameError: name 'something' is not defined

?

2. SyntaxError:解釋器語法錯誤,是唯一不在運行時發(fā)生的異常

>>> 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

定義了進(jìn)行異常監(jiān)控的一段代碼,并提供了處理異常的機制

try:

?? try_suite #監(jiān)控異常

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 #監(jiān)控這里的異常

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 #監(jiān)控這里的異常

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 #監(jiān)控這里的異常

except Exception,e:

??? except_suite #異常處理代碼

?

Exception是大部分異常類的基類,因此上述代碼支持捕獲大多異常。KeyboardInterrupt(用戶中斷執(zhí)行Ctrl+C)和SystemExit(python解釋器請求退出)不是由于代碼錯誤條件引起的異常,如下為異常類的樹:

-BaseException

? |- KeyboardInterrupt

? |- SystemExit

? |- Exception

???? |-所有內(nèi)建異常

?

try-except的作用是提供一個可以提示錯誤或處理錯誤的機制,而不是一個錯誤過濾器,下面這種捕獲所有異常并忽略錯誤不是一種合理的編程方式:

try:

??? …

except: Exception:

?? pass

?

避免把大片代碼裝入try-except中然后使用pass忽略掉錯誤。

可以捕獲特定的異常并忽略它們,或是捕獲所有的異常并采取特定的動作。

v異常參數(shù):

異常也可以有參數(shù),標(biāo)準(zhǔn)內(nèi)建異常提供至少一個參數(shù),指示異常原因的一個字符串

異常參數(shù)自身會組成一個元組,并存儲為異常類的實例。

對于大多數(shù)內(nèi)建異常,也就是從StandardError派生的異常,這個元組中只包含一個指示錯誤原因的字符串。操作系統(tǒng)或其他環(huán)境類型的錯誤,例如:IOError,元組中會把操作系統(tǒng)的錯誤編號放到錯誤字符串的前面

?

>>> 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-finally

try:

??? try-suite

finally:

??? finally-suite #無論如何都執(zhí)行

finally子句是無論異常是否發(fā)生,是否捕獲都會執(zhí)行的一段代碼

當(dāng)在try范圍中產(chǎn)生一個異常時,會立即跳轉(zhuǎn)到finally語句段,當(dāng)finally中的所有代碼都執(zhí)行完畢后,會繼續(xù)向上一層引發(fā)異常。

如果finally中的代碼引發(fā)了另一個異常或由于return、break、continue語法而終止,原來的異常將丟失而且無法重新引發(fā)。

try-except-else-finally

在try語句塊中所有代碼都執(zhí)行成功后,將會執(zhí)行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語句塊中異常發(fā)生點后的剩余語句將被忽略,不會被執(zhí)行,解釋器將搜索處理器,一旦找到,就開始執(zhí)行處理器中的代碼。如果沒有找到合適的處理器,那么異常就向上移交給調(diào)用者去處理,如果上層調(diào)用者也沒有找到合適的處理器,則該異常會繼續(xù)被向上移交,直到找到合適的處理器,如果到達(dá)最頂層仍然沒有找到對應(yīng)處理器,那么就認(rèn)為該異常未處理,解釋器會顯示出跟蹤記錄,然后退出。

?

之前看到的異常都是由解釋器觸發(fā)的。程序員也可以在遇到錯誤時主動觸發(fā)異常:

raise [SomeException, [args [, traceback]]]

SomeException:可以是異常類或?qū)嵗?#xff0c;如果是一個實例,則不能再帶args參數(shù)

args: 異常參數(shù)

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:3

sys模塊中的exc_info()函數(shù),是另一種獲取異常信息的途徑,它提供了一個三元祖信息,比我們單純用異常參數(shù)獲取的信息多

>>> 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: 跟蹤記錄對象

?

?

斷言是一句等價于布爾真的判定,如果表達(dá)式為假,觸發(fā)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 >>>

?

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/TonyZhao/p/3530944.html

總結(jié)

以上是生活随笔為你收集整理的Python基础(10) - 异常的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。