
说明
1、当通过except捕捉到一个异常A后,可以用raise语句再次抛出一个异常B。
然后我们看到的异常信息是B的信息。但我们不知道这个异常B来自哪里,此时,我们可以使用异常链。
2、在抛出异常链时,使用raisefrom语句。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | >>> def func():
... raise IOError
...
>>> try :
... func()
... except IOError as exc:
... raise RuntimeError( 'Failed to open database' ) from exc
...
Traceback (most recent call last):
File "<stdin>" , line 2, in <module>
File "<stdin>" , line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>" , line 4, in <module>
RuntimeError: Failed to open database
|
以上就是python异常链的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。