《python》学习笔记(Day1++),try\except\finally机制
2016-01-18 16:59
423 查看
一、异常处理。保护try内的语句,如果出现异常,由except组处理,finally组内的语句为保证必须运行的代码,无论有无异常,都要执行。
try:
data=open('its.txt','w')
print>>data,'it\'s the ending.' #(保护的语句,出现异常,执行except)
except IOError as err:
print 'File Error:'+str(err) # (err表示特定异常类型,需转换为字符串格式输出)
finally:
if 'data'in locals(): #(文件关闭前,确保存在文件名,以免出现错误)
data.close() #(无论有无异常,确保文件关闭)
二、with重写try\except\finally代码。
try:
with open('its.txt','w') as data:
print>>data,'it\'s the ending.' #(保护的语句,出现异常,执行except)
except IOError as err:
print 'File Error:'+str(err) # (err表示特定异常类型,需转换为字符串格式输出)
try:
data=open('its.txt','w')
print>>data,'it\'s the ending.' #(保护的语句,出现异常,执行except)
except IOError as err:
print 'File Error:'+str(err) # (err表示特定异常类型,需转换为字符串格式输出)
finally:
if 'data'in locals(): #(文件关闭前,确保存在文件名,以免出现错误)
data.close() #(无论有无异常,确保文件关闭)
二、with重写try\except\finally代码。
try:
with open('its.txt','w') as data:
print>>data,'it\'s the ending.' #(保护的语句,出现异常,执行except)
except IOError as err:
print 'File Error:'+str(err) # (err表示特定异常类型,需转换为字符串格式输出)
相关文章推荐
- Python面试题----求出哪个用户的广告费最高
- python(1) - 数据类型和变量
- 自学Python七 爬虫实战一
- Python流控制- 逻辑运算符
- python数组的使用
- Python字符串基础一
- Python 序列通用操作介绍
- python 列表与元组的操作简介
- Python字节流打包拆包
- [python] - pdb调试
- python 内部执行原理
- Python 4.4 获取对象信息
- 【详解】Python脚本转可执行文件进阶版
- python 流控制 if else, elif
- python之路——MySQL数据库
- python 内置函数
- python 升级安装新版本及readline
- python的PIL库安装
- Java和Python运行速度对比
- python 打包与部署