Re: ifstream exception handling
moi5imail@gmail.com wrote:
In the following code I catch general ios_base::failure, then
checks ifstream state. Is there EOF as separate exception of
any status withing exception instance.
You never want an exception for eofbit. It's basically an
internal state, only relevant once you've failed. (In general,
I question the wisdom of using exceptions for failbit. But it
probably depends on exactly what you are doing.)
Anyway, is this code optimal?
ifstream ifs;
try
{
ifs.exceptions(ios_base::eofbit | ios_base::failbit |
ios_base::badbit);
ifs.open(strFileName);
//read operation
}
catch(ios_base::failure &f)
{
if(ifs.eof()!=0)
{
//here I conclude EOF was reached
return;
}
cout << "Critical failure while... " << f.what() << '\n';
}
Several problems:
-- You cannot distinguish between a read error and something
like file not found. This is almost never acceptable.
-- You're likely to stop one input too soon, because the stream
has seen eof while reading ahead. Thus, for example, if
you're reading int's, and the file ends with an int (no
final newline), you'll probably get the exception when
reading the last int, even though it is correct.
In most cases, it is more reasonable to explicitly check for
failure after each input, reserving exceptions for badbit (but
there are exceptions). And you should never trigger exceptions
on eofbit, because its status isn't well defined. (Note that it
isn't taken into accound in ios::fail(), nor in operator void*()
or operator!().)
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]