zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    TCP的状态 (SYN, FIN, ACK, PSH, RST, URG)
    理论基础+实战控制台程序实现AutoFac注入
    C# class 浅拷贝 与 深拷贝
    给定一个矩阵 A, 返回 A 的转置矩阵。
    [弹出消息] C#ShowMessageBox帮助类
    [弹出消息] C#MessageBox帮助类 (转载)
    [XML] C#XMLProcess操作Xml文档的帮助类 (转载)
    [XML] C# XmlHelper操作Xml文档的帮助类 (转载)
    [XML] resources的Xml配置文件 (转载)
    [XML] Resource帮助类
  • 原文地址:https://www.cnblogs.com/wanpython/p/3095530.html
Copyright © 2011-2022 走看看