【问题标题】:C++ File Closure in try/catch blocktry/catch 块中的 C++ 文件关闭
【发布时间】:2018-02-24 01:47:21
【问题描述】:

正确吗?写:

try {
  fstream file;
  file.open(....);
  f(x);   // this function may throw an exception
  ...
  file.close();
} catch {
  ...
}

我想知道如果try块内的函数抛出异常,文件是否会被关闭?

【问题讨论】:

  • 是的,它会的,因为文件对象的析构函数会这样做。
  • 顺便说一句,closure 意味着 C++ 中的其他东西 ...

标签: c++ file try-catch


【解决方案1】:

首先,您的调用file.close(); 是不必要的:省略它没有区别,因为对象file 无论如何都会在销毁时关闭。

无论trycatch块中是否抛出异常,在任何情况下都会调用file的第二个析构函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2011-03-22
    • 2015-09-23
    • 1970-01-01
    • 2020-04-02
    • 2016-07-02
    • 2010-10-31
    相关资源
    最近更新 更多