导航:首页 > 编程语言 > 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异常类相关的资料

热点内容
程序员培训学校排名 浏览:583
oppo手机如何解开微信的加密 浏览:32
学校论文答辩源码 浏览:60
rp在单片机中 浏览:172
linux软件运行命令 浏览:352
stcid加密程序 浏览:134
把解压包子放到水里 浏览:280
phpmongodb连接池 浏览:940
日本解压捏泡泡纸 浏览:115
环保参比算法 浏览:407
解压中的删掉是什么意思 浏览:763
王牌竞速什么时候能停止维修服务器 浏览:485
pdf阅读器官方 浏览:84
程序员那么爱心 浏览:304
字符a经过md5加密 浏览:416
绿色的小蝴蝶是个什么app 浏览:14
python编程输入数字输出年月日英文 浏览:627
程序员枪手 浏览:748
gm28服务器怎么设置 浏览:543
饿了么网站源码 浏览:332