Python的异常处理

1.raise语句

为了引发异常,可以使用一个类或者实例调用raise语句。

raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception


raise Exception('hyperdive overload')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: hyperdive overload

2.捕捉异常


try:
    x=input()
    y=input()
    print x/y
except ZeroDivisionError:
    print "The second number can't be zero"
2
0
The second number can't be zero

3.捕捉多个异常

上述代码只忽略了除数为0的异常,对于其他的异常,依然会出错



所以,我们可以再添加一个except语句,捕捉类型异常

try:
    x=input()
    y=input()
    print x/y
except ZeroDivisionError:
    print "The second number can't be zero"
except TypeError:
    print "That wasn't a number..."


或者,在一个except语句里,多添加几个异常

try:
    x=input()
    y=input()
    print x/y
except(ZeroDivisionError,TypeError,NameError):
    print "Your numbers were bogus"


或者,异常全捕捉

try:
    x=input()
    y=input()
    print x/y
except:
    print "Something wrong happend..."


3.如果你希望程序继续运行,但是又想记录下错误,可以捕捉对象


try:
    x=input()
    y=input()
    print x/y
except(ZeroDivisionError,TypeError,NameError),e:
    print e

异常被打印,程序并没有报错

4.添加else字句,当不报错时,执行代码

while True:
    try:
        x=input()
        y=input()
        print x/y
    except:
        print "Invalid input.Please try again."
    else:
        break





在不报错的时候,退出循环

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值