python如何自定义异常?

Python024

python如何自定义异常?,第1张

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 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

与标准异常相似,大多数异常的命名都以 “Error” 结尾。

很多标准模块中都定义了自己的异常,用以报告在他们所定义的函数中可能发生的错误。

9.8. 异常也是类

用户自定义异常也可以是类。利用这个机制可以创建可扩展的异常体系。

以下是两种新的,有效的(语义上的)异常抛出形式,使用 raise 语句:

raise Class

raise Instance

第一种形式中,Class 必须是 type 或其派生类的一个实例。第二种形式是以下形式的简写:

raise Class()

发生的异常其类型如果是 except 子句中列出的类,或者是其派生类,那么它们就是相符的(反过来说--发生的异常其类型如果是异常子句中列出的类的基类,它们就不相符)。例如,以下代码会按顺序打印 B,C,D:

class B(Exception):

pass

class C(B):

pass

class D(C):

pass

for cls in [B, C, D]:

try:

raise cls()

except D:

print("D")

except C:

print("C")

except B:

print("B")

要注意的是如果异常子句的顺序颠倒过来( execpt B 在最前),它就会打印 B,B,B--第一个匹配的异常被触发。

打印一个异常类的错误信息时,先打印类名,然后是一个空格、一个冒号,然后使用内置函数 str() 将类转换得到的完整字符串。

1、打开Python开发工具IDLE,新建‘myexcept.py’文件,并写代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

这就是自定义定义的异常类,继承自Exception父类,有error字段,__str__函数的作用是打印对象时候,显示的字符串。

2、继续写代码,抛出异常,代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

raisemyException('自定义异常')

3、F5运行程序,在Shell中打印出异常:

Traceback(mostrecentcalllast):

File "C:/Users/123/AppData/Local/Programs/Python/Python36/myexcept.py", line 7, in <module>

raisemyException('自定义异常')

myException:自定义异常

4、下面做测试来捕获这个异常,代码如下;

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

try:

a=0

b=1

ifa!=b:

raisemyException('自定义异常')

exceptmyExceptionase:

print(e)

5、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常

6、也可以直接用Exception来捕获,代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

try:

a=0

b=1

ifa!=b:

raisemyException('自定义异常')

exceptExceptionase:

print(e)

7、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常