std :: ifstream中出现意外异常 [英] Unexpected exception in std::ifstream

查看:2164
本文介绍了std :: ifstream中出现意外异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试I / O我得到一个异常,没有异常应该抛出:

  #include< iostream> 
#include< fstream>

int main()
{
std :: ifstream f(/ tmp);
std :: cout<< Exception Flags:< f.exceptions()<< std :: endl;
if(f>> std :: ws)std :: cout<< 这不会成功< std :: endl;
else std :: cout<< Ok - it failed< std :: endl;
return 0;
}

但输出是:

 异常标志:0 
抛出'std :: ios_base :: failure'实例后调用终止
what():basic_filebuf :: underflow错误阅读文件
中止

g ++(Ubuntu / Linaro 4.7.2-2ubuntu1) 2


$ b

编辑



测试应该失败, p>

从27.5.5.4 basic_ios标志函数


void clear(iostate state = goodbit) ;



4后置条件:如果rdbuf()!= 0,那么state == rdstate();否则rdstate()==(state | ios_base :: badbit)。



5效果:If((state |(rdbuf()?goodbit:badbit))&
exceptions())== 0,返回。否则,该函数将抛出一个
对象失败的类basic_ios :: failure(27.5.3.1.1),它由
实现定义的参数值构造。



void setstate(iostate state);



6效果:调用清除(rdstate()|
state)(可能抛出basic_ios :: failure(27.5.3.1.1) p>


解决方案

这是一个bug,clang v3.4用libc ++ 没有展现这种行为; GCC 4.8的libstdc ++ 仍然



从libstdc ++源和异常的文本,我会说 basic_ios :: clear 不捕获从调用堆栈中抛出的异常,并应用是异常标志在播放? 。



去年已经提出错误53984


Experimenting with I/O I get an exception where no exception should have been thrown:

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream f("/tmp");
    std::cout << "Exception Flags: " << f.exceptions() << std::endl;
    if(f >> std::ws) std::cout << "This will not succeed" << std::endl;
    else std::cout << "Ok - it fails" << std::endl;
    return 0;
}

But the output is:

Exception Flags: 0
terminate called after throwing an instance of 'std::ios_base::failure'
  what():  basic_filebuf::underflow error reading the file
Aborted

g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2

Edit

The test is supposed to fail without exception:

From 27.5.5.4 basic_ios flags functions

void clear(iostate state = goodbit);

4 Postcondition: If rdbuf()!=0 then state == rdstate(); otherwise rdstate()==(state | ios_base::badbit).

5 Effects: If ((state | (rdbuf() ? goodbit : badbit)) & exceptions()) == 0, returns. Otherwise, the function throws an object fail of class basic_ios::failure (27.5.3.1.1), constructed with implementation-defined argument values.

void setstate(iostate state);

6 Effects: Calls clear(rdstate() | state) (which may throw basic_ios::failure (27.5.3.1.1)).

解决方案

It's a bug, and clang v3.4 with libc++ doesn't exhibit this behaviour; GCC 4.8's libstdc++ still does.

From the libstdc++ source and the text of the exception, I'd say that basic_ios::clear is not catching exceptions thrown from down the call stack and applying the "are exception flags in play?" logic before potentially rethrowing them.

It was already raised last year as bug 53984.

这篇关于std :: ifstream中出现意外异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆