C++ STL 流buf 异常处理

C++ STL streambuf exception handling

提问人:hovnatan 提问时间:12/19/2015 最后编辑:hovnatan 更新时间:12/19/2015 访问量:557

问:

在这里,我有这个结构(从这里修改 http://wordaligned.org/articles/cpp-streambufs),我尝试从代码中的两个点开始。但是我永远无法捕捉到这些异常,并且程序正常退出。这是什么原因?streambufostreamthrowmain()

#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++ 异常 stl iostream streambuf

评论


答:

3赞 Dietmar Kühl 12/19/2015 #1

默认情况设置为具有捕获所有内容的 extion 掩码。如果要使异常在流中传播,则需要设置异常掩码以允许这样做。

具体来说,您需要设置以重新引发异常(在流上设置后):std::ios_base::badbitstd::ios_base::badbit

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