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…
打算以后看到相关应用再补充…