Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

34. Python 自定义异常 Exception

在本教程中,我们将学习Python自定义异常。如果您不了解Python异常处理,我们建议您阅读上一个教程.

Python自定义异常

在Python异常处理教程中,我们讨论了什么是异常。基本上,例外意味着事情没有相应地发展。在前面的教程中,我们讨论了不同类型的内置异常。然而,有时内置的异常不足以满足我们的需要,那么我们可以定义自己的自定义异常。

使用assert语句的Python自定义异常

使用断言语句可以最初创建自己的异常。基本上断言语句检查条件。如果不满足条件,它将抛出AssertionError。假设您编写了一个函数,其中将年龄作为参数。如果年龄小于18岁,你不想让程序员使用这个函数。所以函数应该是。


def input_age(age):
   try:
       assert int(age) > 18
   except ValueError:
       return "ValueError: Cannot convert into int"
   else:
       return "Age is saved successfully"


print(input_age("23"))  # This will print
print(input_age(25))  # This will print
print(input_age("nothing"))  # This will raise ValueError which is handled
print(input_age("18"))  # This will raise AssertionError and the the program collapse
print(input_age(43))  # This will not print

以下程序的输出将是


Age is saved successfully
Age is saved successfully
ValueError: Cannot convert into int

Traceback (most recent call last):
  File "/home/imtiaz/ExceptionHandling.py", line 13, in 
    print(input_age("18"))  # This will raise AssertionError the the program collapse
  File "/home/imtiaz/ExceptionHandling.py", line 3, in input_age
    assert int(age) > 18
AssertionError

提出例外

您可以使用提升关键字。所以,你只要写提升关键字,然后是异常的名称。如果我们修改之前的代码,我们得到


def input_age(age):
   try:
       if(int(age)<=18):
           raise ZeroDivisionError
   except ValueError:
       return "ValueError: Cannot convert into int"
   else:
       return "Age is saved successfully"


print(input_age("23"))  # This will execute properly
print(input_age("18"))  # This will not execute properly

代码的输出将是


Age is saved successfully
Traceback (most recent call last):
  File "/home/imtiaz/ExceptionHandling.py", line 12, in 
    print(input_age("18"))  # This will not print
  File "/home/imtiaz/ExceptionHandling.py", line 4, in input_age
    raise ZeroDivisionError
ZeroDivisionError

虽然,这个例外并不是因为被零除,但我们还是看到了。因为我们提出了零除法错误。

Python自定义异常类

Python允许程序员创建自己的异常类。异常通常应该直接或间接地从异常类派生。在下面的示例中,我们创建自定义异常类UnderAge that is derived from the base class Exception.

同样,在另一种方法中,如果条件不满足,我们将引发未成年异常。下面的代码将给您一些关于这个想法的见解。


class UnderAge(Exception):
   pass

def verify_age(age):
   if int(age) < 18:
       raise UnderAge
   else:
       print("Age: "+str(age))

# main program
verify_age(23)  # won"t raise exception
verify_age(17)  # will raise exception

输出将是

所有关于Python的自定义异常。希望,一切都更容易理解。如需进一步查询,请使用下面的注释框。

参考文献:Python用户定义的异常官方文档