Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Boost io streams, error handling

Is it possible to make a custom stream work like the stanadrd ones in regard for errors? That is by default use the good/fail/bad/eof bits rather than exceptions?

The boost docs only mention throwing an std::failure for stream errors and letting other error propagate (eg a badalloc from trying to allocate a buffer), however the boost code does not seem to catch these, instead relying on the user code to handle them, but all my existing code relies on the good(), bad() etc methods and the clear() method in cases where it needs to try again after an error.

like image 921
Fire Lancer Avatar asked May 08 '26 04:05

Fire Lancer


1 Answers

From http://www.trip.net/~bobwb/cppnotes/lec08.htm

The error state can be set using:

void clear(iostate = 0);

The default value of zero results in ios_base::goodbit being set.

clear();

is therefore equivalent to

clear(0);

which is equivalent to

clear(ios_base::goodbit);

Note that ios_base::goodbit is a non-zero value. clear() might be used to set one of the other bits as part of a programmer's code for operator>>() for a particular object. For example:

if (bad_char) is.clear(ios_base::badbit); // set istream's badbit

like image 161
gymbrall Avatar answered May 10 '26 18:05

gymbrall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!