Can a file stream destructor throw an exception, e.g., if file closing operation fails?
auto f = new std::ofstream("data.txt");
f->exceptions(std::ofstream::failbit | std::ofstream::badbit);
...
delete f; // May throw?
Can I prevent such exceptions by closing a stream manually?
auto f = new std::ofstream("data.txt");
f->exceptions(std::ofstream::failbit | std::ofstream::badbit);
...
f->close();
delete f; // May throw?
Throwing from a destructor is dangerous and should be avoided. No object of the C++ standard library throws from its destructor. The C++ language implicitly assumes that destructors are declared as
noexcept.In fact, this is the only difference between
std::basic_filebuf<>::close()andstd::basic_filebuf<>::~std::basic_filebuf(): the latter callsclose()but catches any exception without re-throwing. So, if you want to catch problems with closing the underlying file, you could explicitly callofstream::rdbuf()->close(). Howeverofstream::close()effectively callsrdbuf()->close()and catches any exceptions. In this case, it sets thefailbitand iff you have set the stream's exception mask accordingly (viaofstream::exceptions(), as you did in your question) throws a (different) exception of typestd::ios_base::failure.Thus, to summarize:
close()thestd::ofstream, then, depending on the exception mask of the stream,std::ios_base::failuremay be thrown upon encountering a problem with closing the file.