Reputation: 1161
first, here is some code:
class A
{
public:
A()
{
//...
readTheFile(mySpecialPath);
//...
}
A(boost::filesystem::path path)
{
//...
readTheFile(path);
//...
}
protected:
void readTheFile(boost::filesystem::path path)
{
//First, check whether path exists e.g. by
//using boost::filesystem::exists(path).
//But how to propagate an error to the main function?
}
//...
};
int main(int argc, char **argv)
{
A myClass;
//Some more code which should not be run when A::readTheFile fails
}
What is a good solution to let the main function know that A::readTheFile could not open the file? I want to terminate the execution when opening the file fails.
Many thanks in advance!
Upvotes: 1
Views: 1824
Reputation: 121971
Have readTheFile()
throw an exception:
protected:
void readTheFile(boost::filesystem::path path)
{
//First, check whether path exists e.g. by
//using boost::filesystem::exists(path).
//But how to propagate an error to the main function?
if (/*some-failure-occurred*/)
{
throw std::runtime_error("Failed to read file: " + path);
}
}
...
int main()
{
try
{
A myObj;
//Some more code which should not be run when A::readTheFile fails
}
catch (const std::runtime_error& e)
{
std::cerr << e.what() << "\n";
}
return 0;
}
Upvotes: 3