相关疑难解决方法(0)

使用Python'with'语句时捕获异常

令我遗憾的是,我无法弄清楚如何处理python'with'语句的异常.如果我有一个代码:

with open("a.txt") as f:
    print f.readlines()
Run Code Online (Sandbox Code Playgroud)

我真的想处理'文件未找到异常'以便进行处理.但我不能写

with open("a.txt") as f:
    print f.readlines()
except:
    print 'oops'
Run Code Online (Sandbox Code Playgroud)

并且不能写

with open("a.txt") as f:
    print f.readlines()
else:
    print 'oops'
Run Code Online (Sandbox Code Playgroud)

在try/except语句中包含'with'不起作用:不引发异常.为了以Pythonic方式处理'with'语句内部的失败,我该怎么办?

python exception-handling

258
推荐指数
4
解决办法
16万
查看次数

标签 统计

exception-handling ×1

python ×1