關(guān)于Python中異常(Exception)的匯總
前言
Exception類是常用的異常類,該類包括StandardError,StopIteration, GeneratorExit, Warning等異常類。python中的異常使用繼承結(jié)構(gòu)創(chuàng)建,可以在異常處理程序中捕獲基類異常,也可以捕獲各種子類異常,python中使用try...except語(yǔ)句捕獲異常,異常子句定義在try子句后面。
Python中的異常處理
異常處理的語(yǔ)句結(jié)構(gòu)
try: <statements> #運(yùn)行try語(yǔ)句塊,并試圖捕獲異常 except <name1>: <statements> #如果name1異常發(fā)現(xiàn),那么執(zhí)行該語(yǔ)句塊。 except (name2, name3): <statements> #如果元組內(nèi)的任意異常發(fā)生,那么捕獲它 except <name4> as <variable>: <statements> #如果name4異常發(fā)生,那么進(jìn)入該語(yǔ)句塊,并把異常實(shí)例命名為variable except: <statements> #發(fā)生了以上所有列出的異常之外的異常 else: <statements> #如果沒(méi)有異常發(fā)生,那么執(zhí)行該語(yǔ)句塊 finally: <statement> #無(wú)論是否有異常發(fā)生,均會(huì)執(zhí)行該語(yǔ)句塊。
說(shuō)明
- else和finally是可選的,可能會(huì)有0個(gè)或多個(gè)except,但是,如果出現(xiàn)一個(gè)else的話,必須有至少一個(gè)except。
- 不管你如何指定異常,異??偸峭ㄟ^(guò)實(shí)例對(duì)象來(lái)識(shí)別,并且大多數(shù)時(shí)候在任意給定的時(shí)刻激活。一旦異常在程序中某處由一條except子句捕獲,它就死掉了,除非由另一個(gè)raise語(yǔ)句或錯(cuò)誤重新引發(fā)它。
raise語(yǔ)句
raise語(yǔ)句用來(lái)手動(dòng)拋出一個(gè)異常,有下面幾種調(diào)用格式:
- raise #可以在raise語(yǔ)句之前創(chuàng)建該實(shí)例或者在raise語(yǔ)句中創(chuàng)建。
- raise #Python會(huì)隱式地創(chuàng)建類的實(shí)例
- raise name(value) #拋出異常的同時(shí),提供額外信息value
- raise # 把最近一次產(chǎn)生的異常重新拋出來(lái)
- raise exception from E
例如:
拋出帶有額外信息的ValueError: raise ValueError('we can only accept positive values')
當(dāng)使用from的時(shí)候,第二個(gè)表達(dá)式指定了另一個(gè)異常類或?qū)嵗?,它?huì)附加到引發(fā)異常的__cause__
屬性。如果引發(fā)的異常沒(méi)有捕獲,Python把異常也作為標(biāo)準(zhǔn)出錯(cuò)消息的一部分打印出來(lái):
比如下面的代碼:
try: 1/0 except Exception as E: raise TypeError('bad input') from E
執(zhí)行的結(jié)果如下:
Traceback (most recent call last): File "hh.py", line 2, in <module> 1/0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "hh.py", line 4, in <module> raise TypeError('bad input') from E TypeError: bad input
assert語(yǔ)句
assert主要用來(lái)做斷言,通常用在單元測(cè)試中較多,到時(shí)候再做介紹。
with...as語(yǔ)句
with語(yǔ)句支持更豐富的基于對(duì)象的協(xié)議,可以為代碼塊定義支持進(jìn)入和離開(kāi)動(dòng)作。
with語(yǔ)句對(duì)應(yīng)的環(huán)境管理協(xié)議要求如下:
- 環(huán)境管理器必須有
__enter__
和__exit__
方法。
__enter__
方法會(huì)在初始化的時(shí)候運(yùn)行,如果存在ass子在, __enter__
函數(shù)的返回值會(huì)賦值給as子句中的變量,否則,直接丟棄。
代碼塊中嵌套的代碼會(huì)執(zhí)行。
如果with代碼塊引發(fā)異常, __exit__(type,value,traceback)
方法就會(huì)被調(diào)用(帶有異常細(xì)節(jié))。這些也是由 sys.exc_info返回的相同值.如果此方法返回值為假,則異常會(huì)重新引發(fā)。否則,異常會(huì)終止。正常 情況下異常是應(yīng)該被重新引發(fā),這樣的話才能傳遞到with語(yǔ)句之外。
如果with代碼塊沒(méi)有引發(fā)異常, __exit__
方法依然會(huì)被調(diào)用,其type、value以及traceback參數(shù)都會(huì)以None傳遞。
下面為一個(gè)簡(jiǎn)單的自定義的上下文管理類。
class Block: def __enter__(self): print('entering to the block') return self def prt(self, args): print('this is the block we do %s' % args) def __exit__(self,exc_type, exc_value, exc_tb): if exc_type is None: print('exit normally without exception') else: print('found exception: %s, and detailed info is %s' % (exc_type, exc_value)) return False with Block() as b: b.prt('actual work!') raise ValueError('wrong')
如果注銷到上面的raise語(yǔ)句,那么會(huì)正常退出。
在沒(méi)有注銷掉該raise語(yǔ)句的情況下,運(yùn)行結(jié)果如下:
entering to the block this is the block we do actual work! found exception: <class 'ValueError'>, and detailed info is wrong Traceback (most recent call last): File "hh.py", line 18, in <module> raise ValueError('wrong') ValueError: wrong
異常處理器
如果發(fā)生異常,那么通過(guò)調(diào)用sys.exc_info()
函數(shù),可以返回包含3個(gè)元素的元組。 第一個(gè)元素就是引發(fā)異常類,而第二個(gè)是實(shí)際引發(fā)的實(shí)例,第三個(gè)元素traceback對(duì)象,代表異常最初發(fā)生時(shí)調(diào)用的堆棧。如果一切正常,那么會(huì)返回3個(gè)None。
Python的Builtins模塊中定義的Exception
|Exception Name|Description| |BaseException|Root class for all exceptions| | SystemExit|Request termination of Python interpreter| |KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)| |Exception|Root class for regular exceptions| | StopIteration|Iteration has no further values| | GeneratorExit|Exception sent to generator to tell it to quit| | SystemExit|Request termination of Python interpreter| | StandardError|Base class for all standard built-in exceptions| | ArithmeticError|Base class for all numeric calculation errors| | FloatingPointError|Error in floating point calculation| | OverflowError|Calculation exceeded maximum limit for numerical type| | ZeroDivisionError|Division (or modulus) by zero error (all numeric types)| | AssertionError|Failure of assert statement| | AttributeError|No such object attribute| | EOFError|End-of-file marker reached without input from built-in| | EnvironmentError|Base class for operating system environment errors| | IOError|Failure of input/output operation| | OSError|Operating system error| | WindowsError|MS Windows system call failure| | ImportError|Failure to import module or object| | KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)| | LookupError|Base class for invalid data lookup errors| | IndexError|No such index in sequence| | KeyError|No such key in mapping| | MemoryError|Out-of-memory error (non-fatal to Python interpreter)| | NameError|Undeclared/uninitialized object(non-attribute)| | UnboundLocalError|Access of an uninitialized local variable| | ReferenceError|Weak reference tried to access a garbage collected object| | RuntimeError|Generic default error during execution| | NotImplementedError|Unimplemented method| | SyntaxError|Error in Python syntax| | IndentationError|Improper indentation| | TabErrorg|Improper mixture of TABs and spaces| | SystemError|Generic interpreter system error| | TypeError|Invalid operation for type| | ValueError|Invalid argument given| | UnicodeError|Unicode-related error| | UnicodeDecodeError|Unicode error during decoding| | UnicodeEncodeError|Unicode error during encoding| | UnicodeTranslate Error|Unicode error during translation| | Warning|Root class for all warnings| | DeprecationWarning|Warning about deprecated features| | FutureWarning|Warning about constructs that will change semantically in the future| | OverflowWarning|Old warning for auto-long upgrade| | PendingDeprecation Warning|Warning about features that will be deprecated in the future| | RuntimeWarning|Warning about dubious runtime behavior| | SyntaxWarning|Warning about dubious syntax| | UserWarning|Warning generated by user code|
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。
相關(guān)文章
python 基于卡方值分箱算法的實(shí)現(xiàn)示例
這篇文章主要介紹了python 基于卡方值分箱算法的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5單選按鈕控件QRadioButton詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5單選按鈕控件QRadioButton詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02django model通過(guò)字典更新數(shù)據(jù)實(shí)例
這篇文章主要介紹了django model通過(guò)字典更新數(shù)據(jù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04Python使用ftplib實(shí)現(xiàn)簡(jiǎn)易FTP客戶端的方法
這篇文章主要介紹了Python使用ftplib實(shí)現(xiàn)簡(jiǎn)易FTP客戶端的方法,實(shí)例分析了ftplib模塊相關(guān)設(shè)置與使用技巧,需要的朋友可以參考下2015-06-06