Python 异常处理 (四)

来源:互联网 发布:linux mv 覆盖目录 编辑:程序博客网 时间:2024/06/06 23:17

  此篇是本系列的最后一篇,在这一篇中,我们将讲述有关于用户自定义异常的相关知识。


8.用户自定义异常

  Python允许程序员自定义异常,用于描述Python中没有涉及的异常情况,自定义异常按照命名规范以”Error”结尾,显式地告诉程序员这是异常。自定义异常使用raise语句引发,而且只能通过人工方式触发。
  自定义异常类应该总是继承自内置的 Exception 类, 或者是继承自那些本身就是从 Exception 继承而来的类。 尽管所有类同时也继承自 BaseException ,但你不应该使用这个基类来定义新的异常。 BaseException 是为系统退出异常而保留的,比如 KeyboardInterrupt 或 SystemExit 以及其他那些会给应用发送信号而退出的异常。 因此,捕获这些异常本身没什么意义。 这样的话,假如你继承 BaseException 可能会导致你的自定义异常不会被捕获而直接发送信号退出程序运行。
  我们来看一个简单的例子:

>>> 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 <module>__main__.MyError: 'oops!'

在这个例子中,Exception 默认的__init__() 被覆盖。新的方式简单的创建 value 属性。这就替换了原来创建 args 属性的方式。
  异常类中可以定义任何其它类中可以定义的东西,但是通常为了保持简单,只在其中加入几个属性信息,以供异常处理句柄提取。如果一个新创建的模块中需要抛出几种不同的错误时,一个通常的作法是为该模块定义一个异常基类,然后针对不同的错误类型派生出对应的异常子类:

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

  关于Python异常处理有关的内容就介绍到这儿,以后有机会再补充,同时也欢迎读者留言评论。


参考文献

[1] http://www.runoob.com/python/python-exceptions.html
[2] http://blog.csdn.net/sinchb/article/details/8392827
[3] https://segmentfault.com/a/1190000007736783
[4] http://www.tuicool.com/articles/f2uumm
[5] https://docs.python.org/2.7/library/sys.html
[6] http://www.2cto.com/kf/201303/194676.html
[7] http://python.usyiyi.cn/python_278/library/sys.html
[8] https://docs.python.org/2.7/library/traceback.html
[9] https://docs.python.org/2.7/library/exceptions.html
[10] http://blog.csdn.net/liuxiaochen123/article/details/48155995
[11] https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/
[12] http://blog.csdn.net/suwei19870312/article/details/23258495/
[13] https://docs.python.org/release/2.6/whatsnew/2.6.html
[14] http://python3-cookbook.readthedocs.io/zh_CN/latest/c14/p08_creating_custom_exceptions.html
[15] https://docs.python.org/2.7/tutorial/errors.html
以上是本系列的全部参考文献,对原作者表示感谢。

1 0
原创粉丝点击