Link to home
Start Free TrialLog in
Avatar of Hugh McCurdy
Hugh McCurdyFlag for United States of America

asked on

ifstream() -- which error happened? try/catch

Hi,

Background: I have lots of experience in C but not much in C++.

In C, if I call open() or fopen(), I can check the return value to determine if an error happened.  Then I can check errno to determine the error.

However, as I understand it, in C++ it is better to use try/catch so that error handling happens away from the main code area.  I have read several example of using try/catch with ifstream() on the web but the examples are all something like throw ( "An error occurred." );

That doesn't do me much good.  I want to know why I can't open the file.  Handling a permissions error is quite different than handling the file doesn't exist.

It occurs to me that I could throw something that includes errno.  My question is if that's a proper way to handle errors in C++ or should I be doing something else?

My question boils down to what is the correct OOP approach to handling ifstream errors in C++ when I want to know the nature of the error?

Hugh
SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Hugh McCurdy

ASKER

Thanks both of you.  Thanks for the sample code.