【问题标题】:Try Exception in Python在 Python 中尝试异常
【发布时间】:2016-03-12 22:36:31
【问题描述】:

我有一个用 python 编写的代码,如下所示: 尝试加载文件,该文件由不同模块中的函数生成。所以如果文件被删除了,我们需要从这里运行函数并加载文件:

try:
  with (os.path.join(<path>,<filename>)) as f:
      data = json.loads(f.read())
except IOError:
   Call the function to generate the file
   try:
       # To load the file as above try
    except :
       # needed?

您能帮忙处理第二个尝试/异常块中的代码吗?

【问题讨论】:

  • 请选择您的代码并按 Ctrl+K 正确格式化您的代码。仅对内联代码使用反引号 ( ` )。
  • 我已更改,请查看。我想做的,从下面的异常块转到上一个尝试块

标签: python python-2.7 exception-handling try-catch


【解决方案1】:

是的,其他东西(不仅是IOError)可能仍然会出错。

此外,您需要捕获 AttributeError,而不是 IOError,因为这是 with 语句在失败时返回的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多