I’m writing some class which has 2 (main) subsystems. A part depends on boost::filesystem while another part depends on tinyxml. (Basically, it reads an xml, and depending on the data of the xml it uses boost::filesystem‘s functions for more access to other files).
Now both of these are “likely” to throw exceptions. I am wondering how to handle these exceptions:
The class itself -in most circumstances- can’t “fix” an exception and has just to throw it back. (Most probable case would be a faulty input from the user).
However what should one do in such a case? – boost::filesystem & tinyxml both have their own exceptions, which aren’t completely compatible with each other.
Should I just expect the user of this class to handle boost/tinyxml exceptions? – So far the whole usage of these libraries is hidden for the end user.
Should I repackage the extensions into my own? I’m always hesitant of repackaging, as it means a lot of extra try … catch blocks.
What do you recommend me?
It’s impossible to answer this question without an understanding of your code and your coding guidelines, specifically as they relate to exceptions.
But if your coding guidelines permit exceptions, then I suggest a general rule-of-thumb:
Allow exceptions to propagate until they reach a context in which they can be handled properly. If they never reach a context in which they can be handled properly, allow your program to crash. Get a core dump and debug the problem.
“Handling” an exception in a certain context might be as simple as translation it in to an error code or your own exception class, but in this case you should rethrow the new exception and allow it to propagate to a handler.
Don’t implement any form of a catch-all handler for exceptions with the intent of preventing your application from crashing, or even to log the error and die. Instead, implement a system which will generate dumps in the event of an unhandled exception, and let your program die. The dump itself is enough of a log. You don’t want a catch-all because your system is in such a corrupted state that it can’t be recovered from.