
1、概念
(1)发生异常时,它可能具有关联值,也称为异常参数。参数的存在和类型取决于异常类型。如果异常有参数,则它们将作为未处理异常的消息的最后一部分打印。
(2)except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定,它的参数存储在 instance.args 中。为了方便起见,异常实例定义了 __str__(),因此可以直接打印参数而无需引用 .args。也可以在抛出之前首先实例化异常,并根据需要向其添加任何属性。
2、实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | >>> try :
... raise Exception( 'spam' , 'eggs' )
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print( 'x =' , x)
... print( 'y =' , y)
...
<class 'Exception' >
( 'spam' , 'eggs' )
( 'spam' , 'eggs' )
x = spam
y = eggs
|
以上就是python异常参数的介绍,希望对想要学习python的人有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。