title: Should I write the end of the file in the destructor?
body: <p>I have some code which looks a bit like this:</p>
  
  <pre><code>void writeToStream( std::ostream &amp; outputStream )
  {
      MyXmlWriter xmlWriter{ outputStream };
      xmlWriter.addNode();
      xmlWriter.addNode();
      xmlWriter.close(); // should this be called in `MyXmlWriter` destructor?
  }
  </code></pre>
  
  <p>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 <code>xmlWriter.close();</code> 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 <code>file</code> could have exceptions enabled, writes to a file can fail.) Therefore, if the <code>close()</code> function is called in the destructor, then it should be wrapped in a try-catch block which eats all exceptions thrown:</p>
  
  <pre><code>MyXmlWriter::~MyXmlWriter() 
  {
      try
      {
          close();
      }
      catch (...)
      {
      }
  }
  </code></pre>
  
  <p>However, in this case the caller will not be notified about any errors. The function <code>writeToStream()</code> could fail to write the closing xml tags to the file without the caller knowing about it. What is best practice in this situation?</p>