Thursday, July 27, 2006

try/catch with open transaction

something i’m noticing we haven’t been so good about: when you write a try/catch block with an open transaction, make sure that the last line of code in the try block is the CommitTransaction(). if there is code after the Commit() that throws an error, the catch handler will try to rollback a transaction that has already been committed, and that will throw its own unhandled exception.

void dbcall()
{

try
{

ds.OpenConnection();

ds.BeginTransaction();

//db calls here

//make this the
last line of the try block:

ds.CommitTransaction();

}

catch (Exception x)
{

ds.RollbackTransaction();

handleError(x);

return;

}

finally

{

ds.CloseConnection();

}

//put any other code that
happens after you Commit here

}