Re: exception and streambuf
On Feb 24, 5:48 pm, mathieu <mathieu.malate...@gmail.com> wrote:
Dear c++ gurus,
I am trying to understand why the following piece of code is not
throwing any exception on my system. This is a simplified version just
for the demo (*). My implementation of sync always throw just for this
example. I am using Linux/g++ 4.4.5/debian.
Thanks for any clue,
(*)
#include <iostream>
#include <string>
int write_to_stdout(const char* text, size_t length)
{
std::string s ( text, text + length);
std::cout << s << std::endl;
return length;
}
class windowbuf : public std::streambuf {
public:
int sync ();
int overflow (int ch);
};
int windowbuf::sync ()
{
throw "Killing Program"; // where did it go ?
return windowbuf::traits_type::eof();
}
int windowbuf::overflow (int ch)
{
std::streamsize n = pptr () - pbase ();
char buffer;
buffer = ch;
write_to_stdout( &buffer, 1 );
pbump (-n); // Reset pptr().
return 0;
}
int
main (int argc, char*argv[])
{
windowbuf wbuf;
std::ostream wstr(&wbuf);
wstr << "Hello world!" << std::flush;
return 0;
}
What makes you sure that it's not throwing an exception? The
exception should be caught in ostream, and converted into
setting badbit, unless the implementation is defective. You
don't test badbit, so you cannot see if it was thrown or not;
I think you'll find that your output failed. Similarly, if you
set exceptions(std::badbit) on the ostream, you'll get an
exception (but not the one you threw).
This means that there is no way of propagating specific error
information up by means of an exception; if you need specific
information concerning the error at a higher level, the only
solution is to store it in the streambuf, and read it from there
when the higher level detects the error.
--
James Kanze