Ok. It came the time I have to brace myself and start delineating some error handling strategy for my pet project. I'm probably doing this late already since the usual advise is "delineate a rational error handling strategy early in your project and stick to it."
But I understand the operative word in the above quote is rational. And that is what scares me. Everyone I read so far are very clear that there is no clear way to deal with this. Freedom can be a very scary thing, and it doesn't mean we can't go wrong. Probably the best quote I've found so far is "There are two ways to write error-free programs; only the third one works".
So, I won't be asking for specific advise. I understand you can't give it unless I can give a specific example. Which unfortunately for most cases, I can't.
Anyways, the tools I'm going to use are:
* C++ Exceptions,
* Assert,
* Boost::static_assert (compile-time assertions)
* and of course... avoiding errors.
Some notions:
- My project is OOP oriented. Everything is an object. Objects have relations.
- Classes responsibility includes managing themselves.
- Some preconditions, postconditions and invariants are dependant on the programmer, others on user input.
And here goes my first doubt (more to come):
One of the difficulties I'm having is understanding exactly when and how to use exceptions. Here's an example, some classes are instantiated from dat files. If the file is non existing or its data is corrupt this is a runtime error of which there is no solution. The program must abort. Should I throw an exception from within the class even considering that the only way to handle is to abort? And how do I abort gracefully from within a class definition making sure all my resources are cleaned?
Currently what I have is something like this:
Is this correct?Code:// CObject.hpp class objects_file_error : public std::runtime_error { public: objects_file_error(): std::runtime_error("obj.dat file is missing or corrupt.") {} }; class CObject { // inlining it just to cut down on typing virtual bool load(const std::string& id) try { /*...*/ } catch (objects_file_error& err) { /*... here I output the error message ... */ throw; } };
And what about moving user-defined exception classes to their own header file and create some hierarchy from there?