说明
1、当通过except捕捉到一个异常A后,可以用raise语句再次抛出一个异常B。
然后我们看到的异常信息是B的信息。但我们不知道这个异常B来自哪里,此时,我们可以使用异常链。
2、在抛出异常链时,使用raisefrom语句。
实例
>>>deffunc(): ...raiseIOError ... >>>try: ...func() ...exceptIOErrorasexc: ...raiseRuntimeError('Failedtoopendatabase')fromexc ... Traceback(mostrecentcalllast): File"<stdin>",line2,in<module> File"<stdin>",line2,infunc OSError Theaboveexceptionwasthedirectcauseofthefollowingexception: Traceback(mostrecentcalllast): File"<stdin>",line4,in<module> RuntimeError:Failedtoopendatabase
以上就是python异常链的介绍,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。