Python 中用户定义的异常及示例


在本文中,我们将尝试通过示例介绍如何在 Python 中定义自定义异常。

例子:

class CustomError(Exception):
    pass

raise CustomError("Example of Custom Exceptions in Python")

Output: CustomError: Example of Custom Exceptions in Python

当代码出错时,Python会抛出错误和异常,这可能会导致程序突然停止。Python 还借助try-except提供了异常处理方法。一些最常见的标准异常包括 IndexError、ImportError、IOError、ZeroDivisionError、TypeError 和 FileNotFoundError。

Python 中用户定义的异常

异常需要直接或间接从 Exception 类派生。虽然不是强制性的,但大多数异常都被命名为以“Error”结尾的名称,类似于 python 中标准异常的命名。例如,

Python3

# 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 occurred: ', error.value)

输出

A New Exception occurred:  6

自定义异常类

要了解有关 Exception 类的更多信息,请运行以下代码

Python3

help``(Exception)

输出

Help on class Exception in module exceptions:

class Exception(BaseException)
 |  Common base class for all non-exit exceptions.
 |  
 |  Method resolution order:
 |      Exception
 |      BaseException
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from BaseException:
 |  
 |  __delattr__(...)
 |      x.__delattr__('name') <==> del x.name
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __reduce__(...)
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __setattr__(...)
 |      x.__setattr__('name', value) <==> x.name = value
 |  
 |  __setstate__(...)
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  __unicode__(...)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from BaseException:
 |  
 |  __dict__
 |  
 |  args
 |  
 |  message

示例 1:具有多重继承的用户定义类

在下面的文章中,我们创建了一个名为“Error”的类,该类派生自 Exception 类。这个基类被各种用户定义的类继承,用于处理不同类型的python引发异常和消息

Python3

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass

class zerodivision(Error):
    """Raised when the input value is zero"""
    pass

try:
    i_num = int(input("Enter a number: "))
    if i_num == 0:
        raise zerodivision
except zerodivision:
    print("Input value is zero, try again!")
    print()

输出

Enter a number: 0
Input value is zero, try again!

示例 2:从超类异常派生错误

当模块需要处理几个不同的错误时,就会创建超类异常。执行此操作的常见方法之一是为该模块定义的异常创建基类。此外,定义了各种子类来为不同的错误条件创建特定的异常类。

Python3

# 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 occurred: ', error.msg)

输出

Exception occurred:  Not Allowed

如何使用标准异常作为类?

运行时错误是一个类,它是当生成的错误不属于任何类别时引发的标准异常。该程序说明了如何使用运行时错误作为基类和网络错误作为派生类。以类似的方式,可以从Python的标准异常派生出异常。

Python3

# 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')


原文链接:codingdict.net