详解在Python程序中自定义异常的方法
发布时间:2020-05-28 03:32:10 所属栏目:Python 来源:互联网
导读:通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。
|
通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。 class Networkerror(RuntimeError): def __init__(self,arg): self.args = arg 在你定义以上类后,你可以触发该异常,如下所示:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
在下面这个例子中,默认的__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
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- python – matplotlib在tkinter画布中的缩放功能
- python – 为什么Photoimage放慢了?
- Windows下Python的Django框架环境部署及应用编写入门
- python – NetworkX Graph对象的’Isomorphic’比较,而不是
- python – Flask:使用全局变量将数据文件加载到内存中
- python – 当我们只提供单个单词的向量时,kmeans如何知道如
- python – print(tabulate(…))到漂亮的打印multiIndex pan
- 用Python编写一个简单的俄罗斯方块游戏的教程
- Python环境变量设置方法
- python – mkvirtualenv ImportError:没有名为stevedore的
