Why are C++ STL iostreams not quot;exception friendlyquot;?(为什么 C++ STL iostreams 不是“异常友好的?)
问题描述
我习惯了 Delphi VCL 框架,其中 TStreams 会在错误时抛出异常(例如,找不到文件,磁盘已满).我正在移植一些代码以使用 C++ STL,并且已被 iostreams 捕获,默认情况下不会抛出异常,而是设置 badbit/failbit flags 代替.
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:为什么会这样 - 对于从一开始就包含异常的语言来说,这似乎是一个奇怪的设计决定?
a: Why is this - It seems an odd design decision for a language built with exceptions in it from day one?
b:如何最好地避免这种情况?我可以生成像我期望的那样抛出的 shim 类,但这感觉就像重新发明轮子.也许有一个 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?
推荐答案
C++ 从一开始就没有例外.C 类"1979 年开始,1989 年添加了异常.同时,
streams 库早在 1984 年就编写好了(后来在 1989 年成为
iostreams
(后来在 1991 年被 GNU 重新实现)),它只是不能在一开始就使用异常处理.
C++ wasn'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 becomesiostreams
in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.
参考:
- Bjarne Stroustrup,C++ 的历史:1979−1991 年
- C++ 库
您可以使用 <代码>.exceptions 方法.
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 << "
";
}
catch (ifstream::failure& e) {
std::cout << "Exception opening/reading file
";
}
}
这篇关于为什么 C++ STL iostreams 不是“异常友好的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ STL iostreams 不是“异常友好的"?
基础教程推荐
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01