码迷,mamicode.com
首页 > 编程语言 > 详细

[python]错误检测及异常处理try-except

时间:2015-11-27 23:23:15      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

1. 简介

要给代码添加错误检测及异常处理,只需要将其封装在try-except中。

try:后面为打算管理的代码

except:处理错误的代码

2. 示例

import os
try:
    path = ‘E:‘
    os.chdir(path)
    filename = raw_input(‘Enter file name: ‘)
    fobj = open(filename, ‘r‘)
    for eachline in fobj:
        print eachline, fobj.close()
except IOError, e:
    print ‘file open error: ‘, e

运行结果:

Enter file name: hello
file open error:  [Errno 2] No such file or directory: ‘hello‘

 

[python]错误检测及异常处理try-except

标签:

原文地址:http://www.cnblogs.com/sophia194910/p/5001859.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!