導航:首頁 > 編程語言 > python異常類

python異常類

發布時間:2025-03-24 16:19:15

A. python如何自定義異常

8.5. 用戶自定義異常
在程序中可以通過創建新的異常類型來命名自己的異常(Python 類的內容請參見 類 )。異常類通常應該直接或間接的從 Exception 類派生,例如:
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value)
...
>>> try:
... raise MyError(2*2)
... except MyError as e:
... print('My exception occurred, value:', e.value)
...
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "
", line 1, in ?
__main__.MyError: 'oops!'
在這個例子中,Exception 默認的 __init__() 被覆蓋。新的方式簡單的創建 value 屬性。這就替換了原來創建 args 屬性的方式。
異常類中可以定義任何其它類中可以定義的東西,但是通常為了保持簡單,只在其中加入幾個屬性信息,以供異常處理句柄提取。如果一個新創建的模塊中需要拋出幾種不同的錯誤時,一個通常的作法是為該模塊定義一個異常基類,然後針對不同的錯誤類型派生出對應的異常子類:
class Error(Exception):
"""Base class for exceptions in this mole."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
與標准異常相似,大多數異常的命名都以 「Error」 結尾。
很多標准模塊中都定義了自己的異常,用以報告在他們所定義的函數中可能發生的錯誤。

閱讀全文

與python異常類相關的資料

熱點內容
華為伺服器如何進陣列卡配置 瀏覽:433
apache伺服器ip地址訪問 瀏覽:716
如何買到安卓手機預裝軟體 瀏覽:535
冤罪百度雲不要壓縮 瀏覽:83
蘇州雲存儲伺服器 瀏覽:173
解壓收納原聲 瀏覽:384
java注冊驗證 瀏覽:372
火花app怎麼上推薦 瀏覽:980
什麼app能游戲投屏到電視上 瀏覽:455
伺服器託管到雲端是什麼意思 瀏覽:835
app保存草稿怎麼用 瀏覽:808
安卓如何進入proumb 瀏覽:144
主機虛擬雲伺服器 瀏覽:619
刪除分區加密的空間會不會恢復 瀏覽:706
京東app客戶上門怎麼看搜索量 瀏覽:741
怎麼在農行app購買黃金 瀏覽:46
c型開發板和單片機 瀏覽:146
虛擬機建立用戶的模板文件夾 瀏覽:904
無錫代碼編程培訓班 瀏覽:632
eps圖形數據加密 瀏覽:933