Python异常处理

try/except语句:

python中的try语句可以让程序在出现异常的时候不终止继续执行。

for i in [-1, 0, 1, 2, 3]:
    try:
        print 100/i
    except:
        pass

执行结果:

-100
100
50
33

可见i=0时出现的异常被略过了。

try语句必须与except或finally一起使用,except用于对异常进行处理,例如打印一些有用的信息:

for i in [-1, 0, 1, 2, 3]:
    try:
        print 100/i
    except:
        print 'divided by zero!'

执行结果:

-100
divided by zero!
100
50
33

except还可以分别对不同的错误类进行处理,例如:

for i in [-1, 0, 1, 2, '']:
    try:
        print 100/i
    except ZeroDivisionError:
        print 'divided by zero!'
    except:
        print 'other error!'

python提供了很多的错误类,详情可见我是爱哭鬼的博客。如果想知道错误信息和错误类型,可以用下面的方法:

for i in [-1, 0, 1, 2, '']:
    try:
        print 100/i
    except Exception, e:
        print repr(e)

执行结果:

-100
ZeroDivisionError('integer division or modulo by zero',)
100
50
TypeError("unsupported operand type(s) for /: 'int' and 'str'",)

如果想要得到像不加try语句时得到的回溯信息,可以添加traceback模块:

import traceback

for i in [-1, 0, 1, 2, '']:
    try:
        print 100/i
    except Exception, e:
        print traceback.print_exc()

执行结果:

-100
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print 100/i
ZeroDivisionError: integer division or modulo by zero
None
100
50
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print 100/i
TypeError: unsupported operand type(s) for /: 'int' and 'str'
None

try/finally语句

在使用try语句后,如果某条语句出现异常,则它后面的语句不会被执行,程序直接跳到try之外的语句继续运行。finally语句的作用在于,无论try中的语句是否出现异常,finally中的语句一定会被执行,例如:

for i in [-1, 0, 1, 2, '']:
    try:
        print 100/i
        print "will not be excuted if exception"
    except:
        pass
    finally:
        print "always be excuted"

执行结果:

-100
will not be excuted if exception
always be excuted
always be excuted
100
will not be excuted if exception
always be excuted
50
will not be excuted if exception
always be excuted
always be excuted

raise语句

raise语句用于引发异常,使用时后面跟引发的异常的名称,具体异常类见上面的链接。此时会创建一个该异常类的对象,可以用你想打印的异常信息对该对象进行初始化,例如:

a = 'Hello'

if a == 'Hello':
    raise TypeError('test the raise statement!')

执行结果:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    raise TypeError('test the raise statement!')
TypeError: test the raise statement!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值