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

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'
原文地址:https://www.cnblogs.com/sophia194910/p/5001859.html