We help IT Professionals succeed at work.
Get Started

Handle Exceptions during instantiation

rickhill11 asked
Last Modified: 2016-04-06
I have a class that will allocate some memory, open a file, populate a structure, and do some other house keeping.

My current thought is to do something like:

     foo f;  //set 2 flags, one that the memory allocation succeeded, one that there is no open file, so no operations are valid except open()
     if(!f.open("filename")) then do something.
     open() would do all the dirty work, and every method in the class, would first check to see if a valid file is open and ready for i/o.  This to avoid things like
         foo f;
         f.fetch(); //or whatever would throw an error

The class will be in a static library or DLL, and will be used by many different programs in the Windows environment; although, I might, in my copious free time, try to port to Linux.  

Am I going at this correctly?

One last question, in the case of a failure to open, I want the calling program to decide what to do with the error.  The failure to open might even be anticipated, with some recovery routine.   On the other hand when a programmer does
        foo f;
        f.fetch();   there is no file open, this is programmer's error.  What is the best way to handle this?  It should always stop execution.  I would rather not have to make every call part of an if statement as in if(!f.fetch())... or if(f.valid())f.fetch();
Watch Question
Senior Software Engineer (Avast)
This problem has been solved!
Unlock 1 Answer and 28 Comments.
See Answer
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
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