亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 自定义异常

Python 自定义异常

在本教程中,您将通过示例了解如何根据您的要求定义自定义异常。

Python 有许多内置异常,它们会在程序中出现问题时强制您的程序输出错误。

但是,有时您可能需要创建自己的自定义异常来满足您的目的。


创建自定义异常

在 Python 中,用户可以通过创建新类来定义自定义异常。这个异常类必须直接或间接地从内置的 Exception 班级。大部分内置异常也是从这个类派生的。

>>> class CustomError(Exception):
...     pass
...

>>> raise CustomError
Traceback (most recent call last):
...
__main__.CustomError

>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred

在这里,我们创建了一个名为 CustomError 的用户定义异常 它继承自 Exception 班级。与其他异常一样,可以使用 raise 引发这个新异常 带有可选错误消息的语句。

当我们开发一个大型 Python 程序时,最好将程序引发的所有用户定义的异常放在一个单独的文件中。许多标准模块都这样做。他们将它们的异常分别定义为 exceptions.pyerrors.py (通常但并非总是如此)。

用户定义的异常类可以实现普通类可以做的所有事情,但我们通常使它们简单明了。大多数实现都声明了一个自定义基类并从该基类派生其他异常类。这个概念在下面的例子中更加清晰。


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

在这个例子中,我们将说明如何在程序中使用用户定义的异常来引发和捕获错误。

该程序将要求用户输入一个数字,直到他们正确猜出存储的数字。为了帮助他们弄清楚,提供了一个提示,他们的猜测是大于还是小于存储的数字。

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


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()

print("Congratulations! You guessed it correctly.")

这是该程序的示例运行。

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

我们定义了一个名为 Error 的基类 .

其他两个例外(ValueTooSmallErrorValueTooLargeError ) 实际上由我们的程序引发的都是从这个类派生的。这是在 Python 编程中定义用户自定义异常的标准方式,但您不仅限于这种方式。


自定义异常类

我们可以根据需要进一步自定义这个类以接受其他参数。

学习自定义Exception类,需要具备面向对象编程的基础知识。

访问 Python Object Oriented Programming,开始学习 Python 中的面向对象编程。

我们来看一个例子:

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

输出

Enter salary amount: 2000
Traceback (most recent call last):
  File "<string>", line 17, in <module>
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range

在这里,我们重写了 Exception 的构造函数 类接受我们自己的自定义参数 salarymessage .然后,父Exception的构造函数 使用 self.message 手动调用类 使用 super() 的参数 .

自定义 self.salary 属性被定义为以后使用。

继承的__str__ Exception 的方法 然后使用类在 SalaryNotInRangeError 时显示相应的消息 被提升了。

我们也可以自定义__str__ 通过覆盖方法本身。

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        return f'{self.salary} -> {self.message}'


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

输出

Enter salary amount: 2000
Traceback (most recent call last):
  File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in <module>
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range

要详细了解如何在 Python 中处理异常,请访问 Python 异常处理。


Python

  1. Python 数据类型
  2. Python 运算符
  3. Python pass 语句
  4. Python 函数参数
  5. Python字典
  6. Python 错误和内置异常
  7. Python 面向对象编程
  8. Python 继承
  9. Python 迭代器
  10. Python 中的 type() 和 isinstance() 示例
  11. Python - 异常处理
  12. Python - 面向对象