python 自定義異常


如果你需要自定義異常的話,可以從Exception類派生。 在這個例子中,默認的__init__()異常已被我們重寫。

>>> 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 "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

常見的做法是創建一個由該模塊定義的異常基類和子類,創建特定的異常類不同的錯誤條件。

我們通常定義的異常類,會讓它比較簡單,允許提取異常處理程序的錯誤信息,當創建一個異常模塊的時候,常見的做法是創建一個由該模塊定義的異常基類和子類,根據不同的錯誤條件,創建特定的異常類:

class Error(Exception):
    """Base class for exceptions in this module."""
    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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM