C++STL流异常处理
C++ STL streambuf exception handling
这里有这个streambuf
,ostream
结构(从这里修改http://wordaligned.org/articles/cpp-streambufs),其中我尝试从代码中的两个点throw
。但我永远无法在main()
中捕捉到这些异常,并且程序正常退出。这是什么原因?
#include <iostream>
#include <fstream>
#include <streambuf>
using namespace std;
class teebuf: public streambuf
{
public:
teebuf(streambuf * sb1, streambuf * sb2)
: sb1(sb1) ,
sb2(sb2)
{ }
private:
virtual int overflow(int c) {
if (c == EOF)
return !EOF;
else {
//Throwing here
throw exception();
int const r1 = sb1->sputc(c);
int const r2 = sb2->sputc(c);
return r1 == EOF || r2 == EOF ? EOF : c;
}
}
virtual int sync() {
//Throwing here
throw exception();
int const r1 = sb1->pubsync();
int const r2 = sb2->pubsync();
return r1 == 0 && r2 == 0 ? 0 : -1;
}
private:
streambuf * sb1;
streambuf * sb2;
};
class teestream : public ostream
{
public:
teestream(ostream & o1, ostream & o2);
private:
teebuf tbuf;
};
teestream::teestream(ostream & o1, ostream & o2)
: std::ostream(&tbuf) ,
tbuf(o1.rdbuf(), o2.rdbuf())
{ }
int main() {
ofstream log("hello-world.log");
teestream tee(cout, log);
try {
tee << "Hello, world!n";
} catch(...) {
//Catching here
cerr << "Exception" << endl;
}
return 0;
}
默认情况下,流设置为具有捕获所有内容的exeption掩码。如果你想让异常在流中传播,你需要设置异常掩码来允许这样做
具体来说,您需要设置std::ios_base::badbit
以重新引发异常(在流上设置std::ios_base::badbit
之后):
stream.exceptions(std::ios_base::badbit);
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C++STL流异常处理
- 在低内存情况下使用带有异常处理的STL容器