I'm starting writing class that should read configuration file and initialize some members with data from file. I decided to read this file in constructor. What should constructor do, if something goes wrong, and further construction of object have no sense? For now it displays message:

MultiReader::MultiReader(const char* m_sPath)
{
	fConfigFile.open(m_sPath);
	if(!fConfigFile)
		cout << "Cannot open specified configuration file: "
		<< m_sPath << endl;
}

Call destructor? break illegal here I guess.

MultiReader A;

What will be passed to A in case of such failure?

>What should constructor do, if something goes wrong, and further construction of object have no sense?
Log the error if necessary and throw an exception. Then the code that's trying to create the object can decide what to do.

>What should constructor do, if something goes wrong, and further construction of object have no sense?
Log the error if necessary and throw an exception. Then the code that's trying to create the object can decide what to do.

Can you please give simpliest example?

#include <iostream>
#include <stdexcept>

class EdRules {
public:
  EdRules();
};

EdRules::EdRules()
{
  throw std::exception("Ed Rules!");
}

int main()
{
  try {
    EdRules ed;
  } catch (const std::exception& ex) {
    std::cout << ex.what() << '\n';
  }
}

What if EdRules is part of another class?
And another class is part of another? Exception catching should be performed in each of these?

> Exception catching should be performed in each of these?
That's the beauty of exceptions. You only need to catch at the point you know how to handle the error. If another class and another don't know how to handle the exception, they just pass it on. If another class doesn't know how to handle the exception but another wants to log it, it can catch and then rethrow:

#include <iostream>
#include <exception>

class EdRules {
public:
  EdRules();
};

EdRules::EdRules()
{
  throw std::exception("Ed Rules!");
}

class AnotherClass {
  EdRules ed;
};

class Another {
  AnotherClass foo;
public:
  Another();
};

Another::Another() try: foo()
{}
catch (const std::exception& ex) {
  std::cout << "Logging in Another\n";
  throw;
}

int main()
{
  try {
    Another topLevel;
  } catch (const std::exception& ex) {
    std::cout << ex.what() << '\n';
  }
}

Pretty confusing I must say... I think I will skip it for now. I don't know final shape of my solution now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.