问题描述
我习惯于Delphi VCL框架,其中TStreams错误抛出异常(例如文件未找到,磁盘已满)。我移植一些代码使用C + + STL,而且已被iostreams捕获,默认情况下不抛出异常,但设置。
I'm used to the Delphi VCL Framework, where TStreams throw exceptions on errors (e.g file not found, disk full). I'm porting some code to use C++ STL instead, and have been caught out by iostreams NOT throwing exceptions by default, but setting badbit/failbit flags instead.
两个问题...
为什么是这样的 - 从第一天开始就有例外情况的语言似乎是一个奇怪的设计决定?
a: Why is this - It seems an odd design decision for a language built with exceptions in it from day one?
b:如何最好地避免这种情况?我可以生产垫片类,如我所料,但这感觉像重塑的轮子。也许有一个BOOST库,以一种更清爽的方式做这个?
b: How best to avoid this? I could produce shim classes that throw as I would expect, but this feels like reinventing the wheel. Maybe there's a BOOST library that does this in a saner fashion?
推荐答案
t从第一天的例外构建。 C with classes从1979年开始,并在1989年增加了例外。同时, streams
库早在1984年就写好了(以后变成 iostreams
a. C++ isn't built with exceptions from day one. "C with classes" started in 1979, and exceptions were added in 1989. Meanwhile, the streams
library was written as early as 1984 (later becomes iostreams
in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.
参考:
- Bjarne Stroustrup, A History of C++: 1979−1991
- C++ Libraries
b。 href =http://en.cppreference.com/w/cpp/io/basic_ios/exceptions> .exceptions
方法。
b. You can enable exceptions with 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";
}
std::cout.flush();
file.close();
return 0;
}
这篇关于为什么C ++ STL iostreams不“异常友好”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!