《笨方法学python-5》之异常处理

1.try…except…

except会捕捉某种异常类型的语句,并执行响应的处理代码,而且程序不会中断。举例:
在没有定义任何变量a的时候,

try:
    print a
except NameError:
    print "Something is not Defined."

print 'We can continue doing sth.'

我们得到的输出为:

Something is not Defined.
We can continue doing sth.

常见的python异常类型有:
这里写图片描述
可以在一个except内捕获多个异常,并且只要在except后面不加任何异常类型,这个except块就可以捕获所有的异常。

except (AttributeError, TypeError, SyntaxError):

可以在代码块里加入else,当没有抛出异常时执行:

try:
    print 'I am right!'
except NameError:
    print "Something is not Defined."
else:
    print 'So there is no exception.'

2.try…finally…

无论try是否抛出异常,finally语句都会执行,一般情况下常用于关闭文件、断开服务器链接等。

try:
    print a
except NameError:
    print "Something is not Defined."
finally:
    print "Even though I have 'finally'."

得到的输出为:

Something is not Defined.
Even though I have 'finally'.

3.raise触发异常

我们可以使用raise自己触发异常:

name = raw_input('Please enter my name.\n>')

if name != 'mrzhang':
    raise NameError('You are wrong.')

注:自己触发的异常类型必须也要是python异常类型。

4.assert断言

断言是指如果所指定的条件不满足,则抛出AssertionError:

>>> x=2
>>> assert x < 1

Traceback (most recent call last):
  File "<pyshell#95>", line 1, in <module>
    assert x < 1
AssertionError

5.with…as…

打算以后看到相关应用再补充…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值