exception handling for raw read

A

Amadeus W.M.

Does iostream::read() throw any exception already, or do I have to
check with iostream::fail()? Like this:


fstream IN("myfile", ios::in | ios::binary);
char buf[100];

IN.read(buf, 100);
if(IN.fail()) throw "bad input";

Is there any other way to catch bad input? I'm guessing not.
 
J

John Harrison

Amadeus W.M. said:
Does iostream::read() throw any exception already, or do I have to
check with iostream::fail()? Like this:


fstream IN("myfile", ios::in | ios::binary);
char buf[100];

IN.read(buf, 100);
if(IN.fail()) throw "bad input";

Is there any other way to catch bad input? I'm guessing not.

You guess wrong

Use ios_base::exceptions to tell your IN object to throw an exception on an
error.

john
 
A

Amadeus W.M.

Amadeus W.M. said:
[quoted text muted]

You guess wrong

Use ios_base::exceptions to tell your IN object to throw an exception on an
error.

Thanks!
How exactly do I do that? I'm away from home and I don't have
Stroustrup's book with me.
 
A

Amadeus W.M.

Amadeus W.M. said:
[quoted text muted]

You guess wrong

Use ios_base::exceptions to tell your IN object to throw an exception on an
error.

john

Ok, I did ios_base::exceptions(ios_base::failbit) and
failure is triggered when a failure occurs, allright.
This is very good, because I'm doing many reads, and I can catch
all and any one of them at the highest level, without having to
check if each one succeeded individually. I guess that's the
purpose of exceptions.

Now, is there any way to make it say where the exception occured?
Something like (__FILE__, __FUNCTION__,__LINE__). Do I derive
my own exception class BadInput : public failure {}; ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,463
Latest member
FinleyMoye

Latest Threads

Top