【Python样例】raise ... from 用法说明
原创
©著作权归作者所有:来自51CTO博客作者Changxing长行的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 使用
raise
抛出新的异常时,倾向于新的异常与旧的异常没有关系; - 使用
raise ... from ...
抛出新的异常时,倾向于新的异常是由旧的异常表现的; - 使用
raise ... from None
抛出新的异常时,不会打印旧的异常(即禁止的异常关联)
参考文档:https://www.python.org/dev/peps/pep-3134/
样例一:
def test1(x):
return 3 / x
if __name__ == "__main__":
try:
test1(0)
except ZeroDivisionError:
raise ValueError("Wrong Parameters")
输出结果:
Traceback (most recent call last):
File "test.py", line 7, in <module>
test1(0)
File "test.py", line 2, in test1
return 3 / x
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 9, in <module>
raise ValueError("Wrong Parameters")
ValueError: Wrong Parameters
在抛出异常的日志中,可以看到日志中对 ZeroDivisionError
和 ValueError
之间是描述是 During handling of the above exception, another exception occurred
,即在处理 ZeroDivisionError
异常时又出现了 ValueError
异常,两个异常之间没有因果关系。
样例二:
def test1(x):
return 3 / x
if __name__ == "__main__":
try:
test1(0)
except ZeroDivisionError as e:
raise ValueError("Wrong Parameters") from e
输出信息:
Traceback (most recent call last):
File "test.py", line 7, in <module>
test1(0)
File "test.py", line 2, in test1
return 3 / x
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 9, in <module>
raise ValueError("Wrong Parameters") from e
ValueError: Wrong Parameters
在抛出异常的日志中,可以看到日志中对 ZeroDivisionError
和 ValueError
之间是描述是 The above exception was the direct cause of the following exception
,即因为 ZeroDivisionError
直接异常导致了 ValueError
异常,两个异常之间有直接因果关系。
样例三:
def test1(x):
return 3 / x
if __name__ == "__main__":
try:
test1(0)
except ZeroDivisionError as e:
raise ValueError("Wrong Parameters") from None
输出信息:
Traceback (most recent call last):
File "test.py", line 9, in <module>
raise ValueError("Wrong Parameters") from None
ValueError: Wrong Parameters
在抛出异常的日志中,可以看到日志只打印了 ValueError
而没有打印 ZeroDivisionError
。