python主动抛出异常raise

1 python主动抛出异常raise

如果程序执行不符合业务规则,此时程序应该主动抛出异常。

python主动抛出异常用raise语句。

1.1 raise用法

raise [异常名称 [(异常描述)]]

1.2 描述

NO用法描述
1raise默认引发RuntimeError
2raise 异常名称引发指定名称的异常
3raise 异常名称(异常描述)引发指定异常并附带描述

1.3 raise默认抛出RuntimeError

示例

>>> raise
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    raise
RuntimeError: No active exception to reraise

1.4 raise抛出指定异常

示例

>>> raise IndexError
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    raise IndexError
IndexError

1.5 raise抛出带描述的指定异常

示例

>>> raise IndexError('string index out of range')
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    raise IndexError('string index out of range')
IndexError: string index out of range

1.6 raise主动抛出异常

示例

>>> def testraise():
    try:
        s=input('请输入一个字母:')
        #判断输入的是否为字母
        if(not s.isalpha()):
            raise ValueError('必须输入字母')
    except ValueError as e:
        print('输入错误:',repr(e))
>>> testraise()
请输入一个字母:6
输入错误: ValueError('必须输入字母')

1.7 raise抛出上下文捕获的异常

示例

>>> def raisenoargs():
    try:
        s=input('请输入一个字母:')
        if(not s.isalpha()):
            raise ValueError('必须输入字母')
    except ValueError as e:
        print('输入错误:',repr(e))
        # raise 不带参数,会将最近上文的错误再抛一次
        raise
>>> raisenoargs()
请输入一个字母:6
输入错误: ValueError('必须输入字母')
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    raisenoargs()
  File "<pyshell#52>", line 5, in raisenoargs
    raise ValueError('必须输入字母')
ValueError: 必须输入字母
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值