搜尋
首頁後端開發Python教學python 異常處理總結

       最近,做個小專案常常會遇到Python 的異常,讓人非常頭疼,故對異常進行整理,避免下次遇到異常不知所措,以下就是對Python 異常進行的整理。

1.Python異常類 

 

異常 描述
NameError 嘗試存取一個沒有申明的變數
ZeroDivisionError 除數為0
SyntaxError 文法錯誤
IndexError 索引超出序列範圍
KeyError 請求一個不存在的字典關鍵字
IOError 輸入輸出錯誤(例如你要讀的檔案不存在)
AttributeError 嘗試存取未知的物件屬性
ValueError 傳給函數的參數型別不正確,例如給int()函數傳入字元

 2.捕獲異常

Python完整的捕獲異常的語句有點像:

try:
 try_suite
except Exception1,Exception2,...,Argument:
 exception_suite
...... #other exception block
else:
 no_exceptions_detected_suite
finally:
 always_execute_suite

額...是不是很複雜?當然,當我們要捕捉異常的時候,並不是必須按照上面那種格式完全寫下來,我們可以丟掉else語句,或者finally語句;甚至不要exception語句,而保留finally語句。額,暈了?好吧,下面,我們就來一一說明啦。

2.1 try...except...語句

 try_suite不消我說大家也知道,是我們需要進行捕獲異常的程式碼。而except語句是關鍵,我們在try捕獲了程式碼段try_suite裡的異常後,將交給except來處理。

 try...except語句最簡單的形式如下:

try:
 try_suite
except:
 exception block
  

  上面except子句不跟任何異常和異常參數,所以無論try捕獲了任何異常,都將交給except子句的exception block來處理。如果我們要處理特定的異常,比如說,我們只想處理除零異常,如果其他異常出現,就讓其拋出不做處理,該怎麼辦呢?這時候,我們就要將except子句傳入異常參數啦!那個ExceptionN就是我們要給except子句的異常類別(請參考異常類別那個表格),表示如果捕獲到這類異常,就交給這個except子句來處理。如:

try:
 try_suite
except Exception:
 exception block
 

舉例:

>>> try:
...  res = 2/0
... except ZeroDivisionError:
...  print "Error:Divisor must not be zero!"
... 
Error:Divisor must not be zero!

看,我們真的捕獲了ZeroDivisionError異常!那麼如果我想捕獲並處理多個異常怎麼辦呢?有兩種方法,一種是給一個except子句傳入多個異常類別參數,另一個是寫多個except子句,每個子句都會傳入你想要處理的異常類別參數。甚至,這兩種用法可以混搭呢!下面我就來舉個例子。

try:
 floatnum = float(raw_input("Please input a float:"))
 intnum = int(floatnum)
 print 100/intnum
except ZeroDivisionError:
 print "Error:you must input a float num which is large or equal then 1!"
except ValueError:
 print "Error:you must input a float num!"

[root@Cherish tmp]# python test.py 
Please input a float:fjia
Error:you must input a float num!
[root@Cherish tmp]# python test.py 
Please input a float:0.9999
Error:you must input a float num which is large or equal then 1!
[root@Cherish tmp]# python test.py 
Please input a float:25.091
4

  上面的例子大家一看都懂,就不再解釋了。只要大家明白,我們的except可以處理一種異常,多種異常,甚至所有異常都可以了。

    大家可能注意到了,我們還沒解釋except子句後面那個Argument是什麼東西?別急,聽我一道來。這個Argument其實是一個異常類別的實例(別告訴我你不知到什麼是實例),包含了來自異常代碼的診斷資訊。也就是說,如果你捕捉了一個異常,你就可以透過這個異常類別的實例來獲得更多的關於這個異常的資訊。例如:

>>> try:
...  1/0
... except ZeroDivisionError,reason:
...  pass
... 
>>> type(reason)
<type 'exceptions.ZeroDivisionError'>
>>> print reason
integer division or modulo by zero
>>> reason
ZeroDivisionError('integer division or modulo by zero',)
>>> reason.__class__
<type 'exceptions.ZeroDivisionError'>
>>> reason.__class__.__doc__
'Second argument to a division or modulo operation was zero.'
>>> reason.__class__.__name__
'ZeroDivisionError'

上面這個例子,我們捕獲了除零異常,但是什麼都沒做。那個reason就是異常類別ZeroDivisionError的實例,透過type就可以看出。

2.2 try ... except... else語句

現在我們來說說這個else語句。 Python中有很多特殊的else用法,例如用於條件和循環。放到try語句中,其作用其實也差不多:就是當沒有偵測到異常的時候,則執行else語句。舉例大家可能更懂:

>>> import syslog
>>> try:
...  f = open("/root/test.py")
... except IOError,e:
...  syslog.syslog(syslog.LOG_ERR,"%s"%e)
... else:
...  syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
... 
>>> f.close()

2.3 finally語句

finally子句是無論是否偵測到異常,都會執行的一段程式碼。我們可以丟掉except子句和else子句,單獨使用try...finally,也可以搭配except等使用。

例如2.2的例子,如果出現其他異常,無法捕獲,程式異常退出,那麼檔案 f 就沒有被正常關閉。這不是我們所希望看到的結果,但是如果我們把f.close語句放到finally語句中,無論是否有異常,都會正常關閉這個文件,豈不是很妙

複製程式碼

>>> import syslog
>>> try:
...  f = open("/root/test.py")
... except IOError,e:
...  syslog.syslog(syslog.LOG_ERR,"%s"%e)
... else:
...  syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
... finally: 
>>>  f.close()
 

3.兩個特殊的處理異常的簡單方法

3.1斷言(assert)

    什麼是斷言,先看文法:

assert expression[,reason]

其中assert是斷言的關鍵字。執行該語句的時候,先判斷表達式expression,如果表達式為真,則什麼都不做;如果表達式不為真,則拋出異常。 reason跟我們之前談到的異常類別的實例一樣。不懂?沒關係,舉例吧!最實在!

>>> assert len('love') == len('like')
>>> assert 1==1
>>> assert 1==2,"1 is not equal 2!"
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AssertionError: 1 is not equal 2!

我們可以看到,如果assert後面的表達式為真,則什麼都不做,如果不為真,就會拋出AssertionErro異常,而且我們傳進去的字串會作為異常類的實例的具體資訊存在。其實,assert異常也可以被try塊捕獲:

>>> try:
...   assert 1 == 2 , "1 is not equal 2!"
... except AssertionError,reason:
...   print "%s:%s"%(reason.__class__.__name__,reason)
... 
AssertionError:1 is not equal 2!
>>> type(reason)
<type 'exceptions.AssertionError'>

3.2.上下文管理(with語句)

如果你使用try,except,finally程式碼只是為了保證共享資源(如文件,資料)的唯一分配,並在任務結束後釋放它,那麼你就有福了!這個with語句可以讓你從try,except,finally解放出來!文法如下:

with context_expr [as var]:
    with_suite

是不是不懂?很正常,舉例!

>>> with open('/root/test.py') as f: 
...   for line in f: 
...     print line 

上面这几行代码干了什么?

    (1)打开文件/root/test.py

    (2)将文件对象赋值给  f

    (3)将文件所有行输出

    (4)无论代码中是否出现异常,Python都会为我们关闭这个文件,我们不需要关心这些细节。

    这下,是不是明白了,使用with语句来使用这些共享资源,我们不用担心会因为某种原因而没有释放他。但并不是所有的对象都可以使用with语句,只有支持上下文管理协议(context management protocol)的对象才可以,那哪些对象支持该协议呢?如下表 

file

decimal.Contex 

thread.LockType 

threading.Lock 

threading.RLock 

threading.Condition 

threading.Semaphore 

threading.BoundedSemaphore

至于什么是上下文管理协议,如果你不只关心怎么用with,以及哪些对象可以使用with,那么我们就不比太关心这个问题

4.抛出异常(raise)

如果我们想要在自己编写的程序中主动抛出异常,该怎么办呢?raise语句可以帮助我们达到目的。其基本语法如下:

raise [SomeException [, args [,traceback]] 
第一个参数,SomeException必须是一个异常类,或异常类的实例

第二个参数是传递给SomeException的参数,必须是一个元组。这个参数用来传递关于这个异常的有用信息。

第三个参数traceback很少用,主要是用来提供一个跟中记录对(traceback)
下面我们就来列举几个 例子:

>>> raise NameError
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError
>>> raise NameError() #异常类的实例
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError
>>> raise NameError,("There is a name error","in test.py")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
>>> raise NameError("There is a name error","in test.py") #注意跟上面一个例子的区别
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: ('There is a name error', 'in test.py')
>>> raise NameError,NameError("There is a name error","in test.py") #注意跟上面一个例子的区别
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: ('There is a name error', 'in test.py')

 其实,我们最常用的还是,只传入第一个参数用来指出异常类型,最多再传入一个元组,用来给出说明信息。如上面第三个例子。

5.异常和sys模块

另一种获取异常信息的途径是通过sys模块中的exc_info()函数。该函数回返回一个三元组:(异常类,异常类的实例,跟中记录对象)

>>> try:
...   1/0
... except:
...   import sys
...   tuple = sys.exc_info()
... 
>>> print tuple
(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer division or modulo by zero',), <traceback object at 0x7f538a318b48>)
>>> for i in tuple:
...   print i
... 
<type 'exceptions.ZeroDivisionError'> #异常类    
integer division or modulo by zero #异常类的实例
<traceback object at 0x7f538a318b48> #跟踪记录对象

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。