介绍一下except的用法和作用?

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 108 收藏 0 点赞 0 评论 0

Python的except用来捕获所有异常, 因为Python里面的每次错误都会抛出 一个异常,所以每个程序的错误都被当作一个运行时错误。

一下是使用except的一个例子:

try:

foo = opne(“file”) #open被错写为opne

except:

sys.exit(“could not open file!”)

因为这个错误是由于open被拼写成opne而造成的,然后被except捕获,所以debug程序的时候很容易不知道出了什么问题

下面这个例子更好点:

try:
foo = opne(“file”) # 这时候except只捕获IOError
except IOError:
sys.exit(“could not open file”)

评论列表
文章目录