Avatar of Hugh McCurdy
Hugh McCurdy
Flag 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
C++

Avatar of undefined
Last Comment
Hugh McCurdy

8/22/2022 - Mon
SOLUTION
jkr

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
ambience

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Hugh McCurdy

ASKER
Thanks both of you.  Thanks for the sample code.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes