Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Troubleshooting
Research
Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

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

Avatar of Hugh McCurdy
Hugh McCurdyFlag for United States of America asked on
C++
3 Comments1 Solution777 ViewsLast Modified:
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
ASKER CERTIFIED SOLUTION
Avatar of ambience
ambienceFlag of Pakistan image

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Commented:
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answers