您的位置:首页 > 编程语言 > Python开发

python Exception

2016-01-29 11:26 405 查看

python 常见的异常:

NameError

ZeroDivisionError

SyntaxError

Index Error

KeyError

AttributeError

ValueError

IOError

TypeError

捕获异常:

try:
A
except (Exception1, Exception2),e:
print str(e)
except (Exception3, Exception4),e:
print str(e)
# 捕获所有的异常
except Exception,e:
print str(e)
else:
B
# 无论有无异常都会执行
final:
C


上下文管理 with

好处: 可以再任务结束时释放资源如:文件(数据,日志,数据库),线程资源,简单同步,数据库连接

使用with,首先要引入from__future__import with_statement

如:

with open('text.txt','r') as file:
for eachLine in file:
# do something


如有有什么异常,也会最后close文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: