【问题标题】:C++ STL streambuf exception handlingC++ STL 流缓冲异常处理
【发布时间】:2016-03-25 17:09:05
【问题描述】:

这里我有这个streambufostream 结构(从这里修改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;
}

【问题讨论】:

    标签: c++ exception-handling stl iostream streambuf


    【解决方案1】:

    默认情况下,流设置为具有捕获所有内容的异常掩码。如果您想通过流传播异常,则需要设置异常掩码以允许这样做。

    具体而言,您需要设置 std::ios_base::badbit 以重新抛出异常(在流上设置 std::ios_base::badbit 之后):

    stream.exceptions(std::ios_base::badbit);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多