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

精通 Python 自定义异常:实战指南

Python 自定义异常

本教程教你如何定义符合需求的自定义异常,并通过实战示例说明。

Python 提供许多内置异常,在程序遇到意外条件时发出错误信号。但有时内置异常无法精确描述你遇到的问题。这时可创建自己的自定义异常类型,使代码更清晰、易维护。


创建自定义异常

在 Python 中定义自定义异常很简单:创建一个继承自内置 Exception 类(或其子类)的新类。大多数标准异常派生自 Exception,所以你的自定义类能无缝集成 Python 错误处理体系。

> >>> 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 抛出,附带可选消息。大型项目中,通常将所有自定义异常放在专用模块(如 exceptions.py 或 errors.py)以便定位维护。


示例:Python 用户定义异常

下面程序演示如何用自定义异常引导用户输入。反复提示用户猜数字直到猜中存储值。通过抛出定制异常提示猜大或猜小。

# 定义 Python 用户定义异常
class Error(Exception):
    """其他异常的基类"""
    pass
class ValueTooSmallError(Error):
    """输入值过小时引发"""
    pass
class ValueTooLargeError(Error):
    """输入值过大时引发"""
    pass
# 目标数字
number = 10
# 持续询问直到猜中
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 为两个特定错误类型提供共同祖先。此方法保持异常层级清晰,若需要可用单个 except Error 捕获所有相关错误。


自定义异常类

自定义异常也可存储额外数据或提供更多信息消息。需重写 __init__ 并可选重写 __str__。下面演示薪资验证场景。

class SalaryNotInRangeError(Exception):
    """输入薪资错误引发的异常。
    Attributes:
        salary -- 导致错误的输入薪资
        message -- 错误解释
    """
    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

重写 __init__ 让异常携带违规值。若想要自定义字符串表示,按下面重写 __str__:

class SalaryNotInRangeError(Exception):
    """输入薪资错误引发的异常。
    Attributes:
        salary -- 导致错误的输入薪资
        message -- 错误解释
    """
    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/user/untitled.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 面向对象编程完全指南:从基础到进阶