首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ streambuf异常处理

C++ streambuf异常处理
EN

Stack Overflow用户
提问于 2015-12-18 22:36:58
回答 1查看 498关注 0票数 1

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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-18 23:24:59

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

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

代码语言:javascript
复制
stream.exceptions(std::ios_base::badbit);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34364968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档