troubleshooting Question

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

Avatar of Hugh McCurdy
Hugh McCurdyFlag for United States of America asked on
C++
3 Comments2 Solutions777 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
ambience

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

Join our community to see this answer!
Unlock 2 Answers and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros