我习惯了 Delphi VCL 框架,其中 TStreams 会在错误时抛出异常(例如,找不到文件,磁盘已满)。我正在移植一些代码以改用 C++ STL,并且已被 iostreams 捕获,默认情况下不抛出异常,而是设置 badbit/failbit flags而是。
两个问题...
a:为什么会这样 - 对于从一开始就包含异常的语言来说,这似乎是一个奇怪的设计决定?
b:如何最好地避免这种情况?我可以生成像我期望的那样抛出的 shim 类,但这感觉就像重新发明轮子。也许有一个 BOOST 库可以更明智地做到这一点?
最佳答案
C++ 从一开始就没有异常(exception)。 “C with classes”始于 1979 年,1989 年加入了异常。同时,
streams
库早在 1984 年就编写好了(后来在 1989 年成为iostreams
(后来重新实现)由 GNU 在 1991 年)),它只是不能在一开始就使用异常处理。引用:
您可以使用 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/