在之前的教程中,我们学习了 Python 中不同的内置异常以及处理异常的重要性。
然而,有时我们可能需要创建自己的自定义异常以满足特定需求。
定义自定义异常
在 Python 中,我们可以通过创建一个继承自内置 Exception
类的新类来定义自定义异常。
以下是定义自定义异常的语法:
class CustomError(Exception):
...
pass
try:
...
except CustomError:
...
在这里,CustomError
是一个继承自 Exception
类的用户定义错误。
注意
- 在开发大型 Python 程序时,一个好的做法是将程序引发的所有用户定义异常放在单独的文件中。
- 许多标准模块将其异常单独定义为
exceptions.py
或errors.py
(通常但不总是)。
示例:Python 用户定义异常
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
number = 18
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")
except InvalidAgeException:
print("Exception occurred: Invalid Age")
输出
如果用户输入 input_num 大于 18,
Enter a number: 45 Eligible to Vote
如果用户输入 input_num 小于 18,
Enter a number: 14 Exception occurred: Invalid Age
在上面的示例中,我们通过创建一个继承自内置 Exception
类的新类,定义了自定义异常 InvalidAgeException
。
在这里,当 input_num 小于 18 时,此代码会生成一个异常。
当异常发生时,try
块内其余的代码将被跳过。
except
块捕获用户定义的 InvalidAgeException
异常,并执行 except
块内的语句。
自定义异常类
我们可以根据需要进一步自定义此类别以接受其他参数。
要了解如何自定义异常类,您需要具备面向对象编程的基础知识。
访问Python 面向对象编程以了解 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
类的构造函数以接受我们自己的自定义参数 salary
和 message
。
然后,使用 super()
手动调用父 Exception
类的构造函数,并传入 self.message
参数。
自定义的 self.salary
属性被定义,以便稍后使用。
然后,当引发 SalaryNotInRangeError
时,使用 Exception
类继承的 __str__
方法显示相应的消息。
另请阅读