Unexpected exception in std::ifstream

情到浓时终转凉″ 提交于 2019-12-17 21:03:49

问题


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)).


回答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.



来源:https://stackoverflow.com/questions/20371956/unexpected-exception-in-stdifstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!