一、异常是什么?
- python提供功能强大的替代解决方案——异常处理机制
- python使用异常对象来表示异常状态,并在遇到错误时引发异常。
- 异常对象未被处理(或捕获)时,程序将终止并显示一条错误消息(traceback)。
- 异常不止是用来显示错误消息,事实上,每个异常都是某个类的实例。你能以各种方式引发和捕获这些实例,从而逮住错误并采取措施,而不是放任整个程序失败。
二、raise语句和自定义异常类
2.1raise语句
要引发异常,可使用raise语句,并将一个类或实例作为参数。将类作为参数时,将自动创建一个实例。
# 通用异常,没有指出出现什么错误
raise Exception
# Exception
# 添加了错误消息hyperdrive overload
raise Exception('hyperdrive overload')
# Exception: hyperdrive overload
很多内置的异常类,都可用于raise语句。
2.2自定义的异常类
虽然内置异常类涉及范围广,能够满足很多需求,但有时你可能想自己创建异常类。
如何创建异常类?就像创建其他类一样,但必须直接或间接的继承Exception(这意味着从任何内置异常类派生都可以)。
class SomeCustomException(Exception):
pass
三、捕获异常
捕获异常就是对异常进行处理。可使用try/except。
x = int(input('input the first number:'))
y = int(input('input the second number:'))
print(x/y)
# input the first number:10
# input the second number:0
# ZeroDivisionError: division by zero
# 为了捕获这种异常并对错误进行处理
try:
x = int(input('input the first number:'))
y = int(input('input the second number:'))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
# input the first number:10
# input the second number:0
# The second number can't be zero!
3.1不用提供参数
本文深入探讨Python中的异常处理机制,包括异常的概念、如何使用raise语句引发异常、自定义异常类的方法,以及如何通过try/except语句捕获并处理异常,确保程序的稳定运行。
2060

被折叠的 条评论
为什么被折叠?



