首頁技術(shù)文章正文

Python2和Python3在處理異常上有哪些區(qū)別?

更新時間:2022-05-13 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班


Python 3版本中的異常處理與Python 2版本主要有以下4點(diǎn)不同:

(1)在Python 2中,所有類型的對象直接被拋出;在Python3中,只有繼承自BaseException的對象才可以被拋出。

(2)在Python 2中,捕獲異常的語法是“except Exception,err”;在Python 3中,引入了as關(guān)鍵字,捕獲異常的語法變更為“exceptException as err”。

(3)在Python 2中,處理異常可以使用“raise Exception,args”或者“raise Exception(args)”兩種語法;在Python 3中,處理異常只能使用“raise Exception(args)”。

(4)Python3取消了異常類的序列行為和message屬性。Python 2和Python 3處理異常的示例代碼如下:

Python 2:

>>> try:
raise TypeError,"類型錯誤"
..
... except TypeError, error:
print error.message
...
類型錯誤

Python3:

>>> try:
raise TypeError("類型錯誤")
...
...except TypeError as error:
print(error)
...
類型錯誤


以上只列舉了Python 2與Python 3的部分區(qū)別,更多內(nèi)容見官方文檔https://docs.python.org/3whatsnew/3.0.html。


分享到:
在線咨詢 我要報名
和我們在線交談!