当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。
例:
>>> a = b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> try :
... a = b... except NameError,e:
... print e
...
name 'b' is not defined
>>> try :
... a = b
... except NameError,e:
... print e
... finally:
... print "finally"
...
name 'b' is not defined
finally
>>>