Python中try,except,else,finally用法

debug

在python中可以使用try except else finally raise等关键字来处理异常,使用方法如下:
try:后面跟着需要执行的语句
except 捕获异常 并处理异常,通常异常有不同类型,可分别处理
else:当try语句块正常执行时,无异常产生,执行else语句块
finally:无论是否有异常产生,均执行
raise: 自定义异常

例:
python
    try:
        print “input an integer"
        a = raw_input(">")
        print "input an integer"
        b = raw_input(">")
        result = int(a)/int(b)
    except ValueError:
        print "please input the correct type of value"
    except ZeroDivisionError:
        print " 0 can not be divided"
    else:
        print "good job!"
    finally:
        print "the calculation finished"

assertion 同样可用于testing 和 debug
当assertion的条件不满足时,程序抛出异常
通常用于处理用户输入错误 或结果错误
语法规则
assert statement, “the exception throwed”

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值