c++ - 为什么 C++ STL iostreams 不是 "exception friendly"?

标签 c++ exception stl iostream

我习惯了 Delphi VCL 框架,其中 TStreams 会在错误时抛出异常(例如,找不到文件,磁盘已满)。我正在移植一些代码以改用 C++ STL,并且已被 iostreams 捕获,默认情况下不抛出异常,而是设置 badbit/failbit flags而是。

两个问题...

a:为什么会这样 - 对于从一开始就包含异常的语言来说,这似乎是一个奇怪的设计决定?

b:如何最好地避免这种情况?我可以生成像我期望的那样抛出的 shim 类,但这感觉就像重新发明轮子。也许有一个 BOOST 库可以更明智地做到这一点?

最佳答案

  1. C++ 从一开始就没有异常(exception)。 “C with classes”始于 1979 年,1989 年加入了异常。同时,streams 库早在 1984 年就编写好了(后来在 1989 年成为 iostreams(后来重新实现)由 GNU 在 1991 年)),它只是不能在一开始就使用异常处理。

    引用:

  2. 可以使用 the .exceptions method 启用异常.

// ios::exceptions
#include <iostream>
#include <fstream>
#include <string>

int main () {
    std::ifstream file;
    file.exceptions(ifstream::failbit | ifstream::badbit);
    try {
        file.open ("test.txt");
        std::string buf;
        while (std::getline(file, buf))
            std::cout << "Read> " << buf << "\n";
    }
    catch (ifstream::failure& e) {
        std::cout << "Exception opening/reading file\n";
    }
}

关于c++ - 为什么 C++ STL iostreams 不是 "exception friendly"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3180268/

相关文章:

c++ - qt项目symbian os兼容性问题?

c++ - 在 C++ 中插入类型映射

c++ - 如何在编译时将 ostream_iterator<> 用于通用容器?

c++ - std::remove_if 移除的元素到哪里去了?

c++ - glRotatef 不旋转任何东西

c++ - 用空 vector 的 M 个元素初始化 vector c++

android.view.InflateException(错误充气类)仅在生产

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

自定义异常中的Java异常NullPointerException

c++ - 从两个线程调用 std::deque 上的删除和push_back是否是线程安全的?