前言
当程序出现错误时,系统会自动触发异常。Python 也允许程序自行引发异常,自行引发异常使用 raise 语句来完成。
- 使用
raise
抛出新的异常 - 使用
raise ... from ...
抛出新的异常时,新的异常是由旧的异常表现的; - 使用
raise ... from None
抛出新的异常时,不会打印旧的异常(即禁止的异常关联)
raise 引发异常
使用 raise 语句,主动引发异常,终止程序
代码语言:javascript复制x = 20
if not isinstance(x, str):
raise Exception("value is not type of str")
else:
print("hello")
运行结果:
代码语言:javascript复制Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 4, in <module>
raise Exception("value is not type of str")
Exception: value is not type of str
当raise 抛出异常时,程序就会终止
try… except 捕获异常
使用try… except 捕获异常
代码语言:javascript复制x = [20, 3, 22, 11]
try:
print(x[7])
except IndexError:
print("index out of list")
运行后不会有异常 在捕获异常后,也可以重新抛一个其它的异常
代码语言:javascript复制x = [20, 3, 22, 11]
try:
print(x[7])
except IndexError:
print("index out of list")
raise NameError("new exception ...")
输出结果:
代码语言:javascript复制Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 4, in <module>
print(x[7])
IndexError: list index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 7, in <module>
raise NameError("new exception ...")
NameError: new exception ...
在抛出异常的日志中,可以看到日志中对 IndexError 和 NameError之间是描述是 During handling of the above exception, another exception occurred,即在处理 IndexError 异常时又出现了 NameError 异常,两个异常之间没有因果关系。
raise … from 用法
示例:
代码语言:javascript复制x = [20, 3, 22, 11]
try:
print(x[7])
except IndexError as e:
print("index out of list")
raise NameError("new exception ...") from e
运行结果
代码语言:javascript复制Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 4, in <module>
print(x[7])
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 7, in <module> raise NameError("new exception ...") from e
NameError: new exception ...
在抛出异常的日志中,可以看到日志中对 IndexError和 NameError 之间是描述是 The above exception was the direct cause of the following exception,即因为 IndexError 直接异常导致了 NameError异常,两个异常之间有直接因果关系。
示例:
代码语言:javascript复制x = [20, 3, 22, 11]
try:
print(x[7])
except IndexError as e:
print("index out of list")
raise NameError("new exception ...") from None
运行结果
代码语言:javascript复制Traceback (most recent call last):
File "D:/demo/untitled1/demo/a.py", line 7, in <module>
raise NameError("new exception ...") from None
NameError: new exception ...
在抛出异常的日志中,可以看到日志只打印了 NameError
而没有打印 IndexError
。