• 技术文章 >Python技术 >Python基础教程

    python异常参数是什么

    小妮浅浅小妮浅浅2021-05-20 09:33:19原创3375

    1、概念

    (1)发生异常时,它可能具有关联值,也称为异常参数。参数的存在和类型取决于异常类型。如果异常有参数,则它们将作为未处理异常的消息的最后一部分打印。

    (2)except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定,它的参数存储在 instance.args 中。为了方便起见,异常实例定义了 __str__(),因此可以直接打印参数而无需引用 .args。也可以在抛出之前首先实例化异常,并根据需要向其添加任何属性。

    2、实例

    >>> 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电脑。

    专题推荐:python异常参数
    品易云
    上一篇:python中except的异常处理 下一篇:python中raise语句的异常引发

    相关文章推荐

    • python变量有几种作用域类型• dict.setdefault()在python中设置默认值• python中defaultdict的初始化• python中setuptools如何安装• python try语句的执行原理• python中except的异常处理

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网