1、概念
(1)发生异常时,它可能具有关联值,也称为异常参数。参数的存在和类型取决于异常类型。如果异常有参数,则它们将作为未处理异常的消息的最后一部分打印。
(2)except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定,它的参数存储在 instance.args 中。为了方便起见,异常实例定义了 __str__(),因此可以直接打印参数而无需引用 .args。也可以在抛出之前首先实例化异常,并根据需要向其添加任何属性。
2、实例
>>>try: ...raiseException('spam','eggs') ...exceptExceptionasinst: ...print(type(inst))#theexceptioninstance ...print(inst.args)#argumentsstoredin.args ...print(inst)#__str__allowsargstobeprinteddirectly, ...#butmaybeoverriddeninexceptionsubclasses ...x,y=inst.args#unpackargs ...print('x=',x) ...print('y=',y) ... <class'Exception'> ('spam','eggs') ('spam','eggs') x=spam y=eggs
以上就是python异常参数的介绍,希望对想要学习python的人有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
上一篇