python:文件异常处理(try-except-finally)

上一篇 / 下一篇  2014-10-28 13:22:46 / 个人分类:python学习

try:
    可能出现异常的语句
except:
   当异常出现时如何处理
finally:
   无论异常是否发生都必须执行的语句

举例说明:
try:
    f=open("..\\1.txt")
    print "File opened!"
except:
    print "File not exists."
finally:
    f.close()
执行上面语句,会报错NameError
>>> ================================ RESTART ================================
>>>
File not exists.
Traceback (most recent call last):
  File "C:\Python27\test\Headfirstpython\test.py", line 7, in <module>
    f.close()
NameError: name 'f' is not defined

>>>
如何处理呢,我们需要做一个判断:如果文件打开,才去关闭。用到python的一个内置函数locals(),作用域内的局部变量集合。
修正如下:
try:
    f=open("..\\1.txt")
    print "File opened!"
except:
    print "File not exists."
finally:
    if "f" in locals():
        f.close()
>>> ================================ RESTART ================================
>>>
File not exists.
>>>
如果想定位一下,到底发生了什么异常,该如何处理呢?
我们可以把异常信息输出
修改如下:
try:
    f=open("..\\1.txt")
    print "File opened!"
except Exception as err:#把异常对象放到except组中,将异常错误的信息准确输出
    print "File not exists:"+str(err)
finally:
    if "f" in locals():#在整个作用域变量集合中搜索f是否存在。
        f.close()
>>> ================================ RESTART ================================
>>>
File not exists:[Errno 2] No such file or directory: '..\\1.txt'
>>>


TAG:

 

评分:0

我来说两句

Open Toolbar