I have posed another question here and I am writing this one for some code review:
class ConfigFile
{
private:
PTree m_ptConfig;
public:
ConfigFile(const std::string& name)
{
json::read_json(name, m_ptConfig);
}
~ConfigFile();
double getVal1()
{
std::string path = "path.to.val1";
double val1 = m_ptConfig.get<double>(path, -1);
if (val1 < 0)
{
std::string msg = "getVal1() failed or val1 < 0";
throw MyConfigFileException(msg);
}
return val1;
}
double getVal2() {/*the same as before*/};
// ... more values the same way
};
The exception class is here:
class MyConfigFileException : public MyIOException // MyIOException is derived from std::exception
{
private:
std::string m_msg;
public:
MyConfigFileException(const std::string msg) : msg(msg) {}
virtual const char* what() const throw()
{
return m_msg.c_str();
}
};
The handling for this kind of exception I have done it in main function:
int main(int argc, char **argv)
{
const std::string configFileName = argv[1];
try
{
RunAlgo algo(configFileName);
algo.runAlgorithm();
}
catch (MyConfigFileException& mcfe)
{
std::cout << "Config File Exception: " << mcfe.what() << std::endl;
return -1;
}
catch (MyIOException& mioe)
{
std::cout << "IOException: " << mioe.what() << std::endl;
return -2;
}
catch (std::exception& e)
{
std::cout << "Unknown exception: " << e.what() << std::endl;
return -3;
}
return 0;
}
I use the chatch blocks to see if it has crashed because of me or not, that is why I just print the message and return a value. (Maybe this is not necessary since it returns a different value, but I let it there for the moment)
In the runAlgorithm() function I have a loop, where I treat another kind of exceptions:
// ...
void RunAlgo::runAlgorithm()
{
ConfigFile cf("config.json")
double v1 = cf.getVal1();
// ...
for (int i = 0; i < 100; i++)
{
// ...
try
{
foo(cf);
}
catch (MyOtherExceptions & moe)
{
std::cout << moe.what() << std::endl;
}
// ...
}
// ...
}
MyOtherException
s are going to be treated separately, like: for the current iteration, there is a problem with a buffer, send a message to a queue.
foo
is implemented here:
void foo(const ConfigFile& cf)
{
double v2 = cf.getVal2();
// some other code that may throw MyOtherException exceptions
}
Do you think I am using the exceptions correctly?
I admit that the handling is not really done, but I am asking if I am doing right with the throw
s and try-catch
blocks, supposing that instead of just printing messages the handling is done (as "sending message to a queue").