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‘
时间: 2024-12-25 06:25:45