Re: Unhandled exception - How to turn off!
Vladimir Nesterovsky wrote:
A valid use of uncaught_exception function is in the RAII e.g:
class TransactionScope
{
private:
Connection &connection;
public:
TransactionScope(Connection &connection): connection(connection)
{
connection.BeginTransaction();
}
~TransactionScope()
{
if (!std::uncaught_exception())
connection.Commit();
else
connection.Rollback();
}
};
...
Connection &connection = ...
{
TransactionScope transactionScope(connection);
...
}
This has the problem that if a TransactionScope object is created in a
destructor, and that destructor is called due to an exception being
thrown, the transaction will always be rolled back.
std::uncaught_exception() could return an int rather than a boolean,
indicating the number of currently active exceptions. Just to clarify:
Foo::~Foo
{
try
{
TransactionScope s(m_connection);
//do some stuff that might throw
}
catch (...)
{
//avoid exception leaving destructor!
//maybe log the fact transaction failed or display an error.
}
}
In that code, the transaction may be rolled back even if it has
completely succeeded. Compare:
class TransactionScope
{
private:
Connection &connection;
int uncaught_exceptions;
public:
TransactionScope(Connection &connection): connection(connection),
uncaught_exceptions(std::uncaught_exception())
{
connection.BeginTransaction();
}
~TransactionScope()
{
//check that we don't have any more exceptions than before!
if (std::uncaught_exception() == uncaught_exceptions)
connection.Commit();
else
connection.Rollback();
}
};
In normal operation, uncaught_exceptions will be 0, but it can be any
number potentially.
Tom