I have some code which looks a bit like this:
void writeToStream( std::ostream & outputStream )
{
MyXmlWriter xmlWriter{ outputStream };
xmlWriter.addNode();
xmlWriter.addNode();
xmlWriter.close(); // should this be called in `MyXmlWriter` destructor?
}
The close function writes some xml close tags so the file can be parsed properly. The constructor writes the header of the xml file. One could consider xmlWriter.close();
clean-up code. It is common advice for C++ to put clean-up code into destructors. This way you can never forget to clean-up properly. However, in our case the clean-up code could throw. (Imagine that file
could have exceptions enabled, writes to a file can fail.) Therefore, if the close()
function is called in the destructor, then it should be wrapped in a try-catch block which eats all exceptions thrown:
MyXmlWriter::~MyXmlWriter()
{
try
{
close();
}
catch (...)
{
}
}
However, in this case the caller will not be notified about any errors. The function writeToStream()
could fail to write the closing xml tags to the file without the caller knowing about it. What is best practice in this situation?