python异常之raise语句

1 python异常之raise语句

python通过raise语句显式触发异常,raise后面跟类名或实例名。

1.1 基本用法

用法

raise <类名>
raise <实例名>
raise

描述

(1) raise <类名>,则python自动调用类的不带参数的构造函数,来触发异常;

(2) raise <实例名>,触发指定实例名的异常;

(3) raise ,重新触发当前异常,通常用于异常处理器中,传递已经捕获的异常;

示例

>>> try:
    raise TypeError
except TypeError:
    print('raise重新引发当前异常')
    raise

raise重新引发当前异常
Traceback (most recent call last):
  File "<pyshell#10>", line 2, in <module>
    raise TypeError
TypeError

1.2 raise from

raise from 用于描述当前异常与except捕获异常的关系。

用法

raise [异常[('异常说明')]]
raise 异常 from 变量
raise 异常 from None

描述

在except分句编写raise时,用于向外传递异常,如果不接参数,则传递except捕获的异常,如果接参数,则传递最新的异常,并且说明与except捕获的异常的关系。

(1) raise [异常[(‘异常说明’)]]:表示raise的异常与except捕获的异常没有直接关系;

(2) raise 异常 from 变量:表示raise的异常由except捕获的异常导致;

(3) raise 异常 from None:不打印except捕获的异常;

1.2.1 raise

描述

raise [异常[(‘异常说明’)]]:表示raise的异常与except捕获的异常没有直接关系;

示例

>>> def testraise(s,i):
    try:
        print(s[i])
    except IndexError:
        raise ValueError('i输入错误')

    
>>> testraise('梯阅线条',5)
Traceback (most recent call last):
  File "<pyshell#17>", line 3, in testraise
    print(s[i])
IndexError: string index out of range
# raise [异常[('异常说明')]] , 捕获except的异常时,触发了另一个异常:raise的异常,两者无直接关系
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    testraise('梯阅线条',5)
  File "<pyshell#17>", line 5, in testraise
    raise ValueError('i输入错误')
ValueError: i输入错误

1.2.2 raise from

描述

raise 异常 from 变量:表示raise的异常由except捕获的异常导致;

示例

>>> def testraise(s,i):
    try:
        print(s[i])
    except IndexError as ie:
        raise ValueError('i输入错误') from ie

    
>>> testraise('梯阅线条',5)
Traceback (most recent call last):
  File "<pyshell#23>", line 3, in testraise
    print(s[i])
IndexError: string index out of range

# raise 异常 from except的异常 , 是由except异常直接引发的
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    testraise('梯阅线条',5)
  File "<pyshell#23>", line 5, in testraise
    raise ValueError('i输入错误') from ie
ValueError: i输入错误

1.2.3 raise from None

描述

raise 异常 from None:不打印except捕获的异常;

示例

>>> def testraise(s,i):
    try:
        print(s[i])
    except IndexError as ie:
        # None 不打印 except的异常
        raise ValueError('i输入错误') from None

    
>>> testraise('梯阅线条',5)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    testraise('梯阅线条',5)
  File "<pyshell#26>", line 5, in testraise
    raise ValueError('i输入错误') from None
ValueError: i输入错误
  • 23
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值