1

ここに、このstreambuf構造ostreamがあります (ここから変更http://wordaligned.org/articles/cpp-streambufs )。ここthrowで、コードの 2 つのポイントから試みます。しかし、これらの例外をキャッチすることはでき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;
}
4

1 に答える 1

3

ストリームは、すべてをキャッチする例外マスクを持つようにデフォルトで設定されています。ストリームを介して例外を伝播する場合は、例外マスクを設定して許可する必要があります。

std::ios_base::badbit具体的には、例外を再スローするように設定する必要があります(std::ios_base::badbitストリームに設定された後):

stream.exceptions(std::ios_base::badbit);
于 2015-12-18T23:24:59.823 に答える