RAII and destructors which throw
When googling on this topic, I ran across this thread which was
started by The Great Scott Myers:
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/9d5324ce02f4d89b/
Simply put, I want to be notified if fclose() fails, and I want to be
notified by an exception; I don't want to use some alternative ad hoc
error reporting scheme just for fclose() and other release failures.
I was surprised the aforementioned thread did not suggest the use of a
(per-thread) global list for accumulating exceptions during unwinding.
Something like:
class file
{
private:
std::FILE* m_file ;
public:
// ...
~file()
{
if( std::fclose(m_file) != 0 )
{
if( std::uncaught_exception() )
{
// already unwinding via exception
additional_exceptions().add(error_close()) ;
}
else
{
throw error_close() ;
}
}
}
} ;
int main()
{
try
{
// ...
}
catch( const error_open & )
{
// ...
}
catch( const error_write & )
{
// ...
if( !additional_exceptions().empty() )
{
for( exception_iterator i =
additional_exceptions().begin() ;
i != additional_exceptions().end() ;
++i )
{
if( dynamic_cast<error_close*>(*i) )
{
// write error followed by a close error ...
}
}
}
}
catch( const error_close & )
{
// ...
}
}
One downside is that the object returned by additional_exceptions()
must contain a fixed-size static list for each type of exception.
Otherwise we would need to call 'new' inside destructors.
The other technicality is ensuring that the list is cleared properly.
One possible way would be to clear the list when the
exception_iterator scope ends.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]