python笔记(9)----异常

Python用异常对象来表示异常情况。遇到错误后,会引发异常,如果异常对象未被处理或捕捉,程序就会用所谓的回溯终止信息,
示例:
print 1/0


结果:
Traceback (most recent call last):
  File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
    print 1/0
ZeroDivisionError: integer division or modulo by zero


raise语句
为了引发异常,可以使用一个类或者实例参数调用raise语句。使用类时,程序会自动创建实例。


示例:
raise Exception


结果:
Traceback (most recent call last):
  File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
    raise Exception
Exception


捕捉异常


示例:
try:
    x=input('enter the first number: ')
    y=input('enter the second number: ')
    print x/y
except ZeroDivisionError:
    print "the second number can't be zero!"


结果:
enter the first number: 3
enter the second number: 0
the second number can't be zero!


用一个块捕捉多个异常


try:
    x=input('enter the first number: ')
    y=input('enter the second number: ')
    print x/y
except (ZeroDivisionError,TypeError,NameError):
    print "your numbers were bogus..."


结果:
enter the first number: 2
enter the second number: 0
your numbers were bogus...


添加else字句


while True:
    try:
        x=input('enter the first number: ')
        y=input('enter the second number: ')
        value = x/y
        print 'x/y',value
    except:
        print 'invalid input.please try again.'
    else:
        break


结果:
enter the first number: 1
enter the second number: 0
invalid input.please try again.
enter the first number: 3
enter the second number: 1
x/y 3


再加上finally语句。
try:
    1/0
except ZeroDivisionError:
    print "Unknown variable"
else:
    print "That went well!"
finally:
    print "Cleaning up."


结果:
Unknown variable
Cleaning up.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值