Throws throws DBTransaction
The documentation says that the rollback method can be thrown when the transaction is not in a pending state (after the start of the transaction and before the transaction is committed).
I cannot find a way to check if a transaction can rollback or not. There is no state property.
a source to share
Ideally, just wrap the transaction with a "using" statement, or use a TransactionScope object that will automatically rollback if an exception is thrown, or if the transaction doesn't commit before it goes out of scope.
The rest of the time, kind of ugly, I usually wrap my rollbacks in an empty try / catch block because it's almost always in the catch handler, which has a more meaningful exception. The idea is that we can only rollback if we can, but we don’t want to start throwing new exceptions if we cannot (for some unpredictable reason), because the transaction will rollback until it is done anyway. You still need to try to clean up properly, so you don't have to wait for the garbage collector, but if you can't, rollback is not a real problem.
try
{
SqlTransaction trans = connection.BeginTransaction();
///blah blah blah
}
catch(Exception theExceptionICareAbout)
{
try
{
if(trans != null)
{
trans.Rollback();
}
}
catch {}
throw; //re-throws the meaningful exception.
}
Note: do not try to repeat the exception (ie "throw theExceptionICareAbout"), because this will recreate the stack trace. Instead, just use "throw", which will continue with the existing exception stack.
a source to share