Python中用户定义的异常及示例
先决条件 - 本文是异常处理的扩展。
当代码出错时, Python会抛出错误和异常,这可能会导致程序突然停止。 Python还借助 try-except 提供了异常处理方法。一些最常见的标准异常包括 IndexError、ImportError、IOError、ZeroDivisionError、TypeError 和 FileNotFoundError。用户可以使用异常类创建自己的错误。
创建用户定义的异常
程序员可以通过创建一个新的异常类来命名他们自己的异常。异常需要直接或间接从 Exception 类派生。尽管不是强制性的,但大多数异常都被命名为以“Error”结尾的名称,类似于Python中标准异常的命名。例如:
PYTHON
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)
PYTHON
help(Exception)
PYTHON
# class Error is derived from super class Exception
class Error(Exception):
# Error is derived class for Exception, but
# Base class for exceptions in this module
pass
class TransitionError(Error):
# Raised when an operation attempts a state
# transition that's not allowed.
def __init__(self, prev, nex, msg):
self.prev = prev
self.next = nex
# Error message thrown is saved in msg
self.msg = msg
try:
raise(TransitionError(2,3*2,"Not Allowed"))
# Value of Exception is stored in error
except TransitionError as error:
print('Exception occured: ',error.msg)
PYTHON
# NetworkError has base RuntimeError
# and not Exception
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Networkerror("Error")
except Networkerror as e:
print (e.args)
输出:
('A New Exception occured: ', 6)
了解异常类
要了解有关 Exception 类的更多信息,请运行以下代码
PYTHON
help(Exception)
从超类异常派生错误
当模块需要处理几个不同的错误时,就会创建超类异常。执行此操作的常用方法之一是为该模块定义的异常创建一个基类。此外,定义了各种子类以针对不同的错误条件创建特定的异常类。
PYTHON
# class Error is derived from super class Exception
class Error(Exception):
# Error is derived class for Exception, but
# Base class for exceptions in this module
pass
class TransitionError(Error):
# Raised when an operation attempts a state
# transition that's not allowed.
def __init__(self, prev, nex, msg):
self.prev = prev
self.next = nex
# Error message thrown is saved in msg
self.msg = msg
try:
raise(TransitionError(2,3*2,"Not Allowed"))
# Value of Exception is stored in error
except TransitionError as error:
print('Exception occured: ',error.msg)
输出:
('Exception occured: ', 'Not Allowed')
如何使用标准异常作为基类?
运行时错误是一个标准异常类,当生成的错误不属于任何类别时会引发该异常。该程序说明了如何使用运行时错误作为基类和网络错误作为派生类。以类似的方式,可以从Python的标准异常中派生异常。
PYTHON
# NetworkError has base RuntimeError
# and not Exception
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Networkerror("Error")
except Networkerror as e:
print (e.args)
输出:
('E', 'r', 'r', 'o', 'r')