首页 > 编程语言 > 详细

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

时间:2015-11-27 23:22:14      阅读:272      评论: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)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!