tags:

views:

485

answers:

3

Is there something wrong with this code?
Sometimes I get an unhandled "Invalid transaction object" exception in it:

procedure BlaBla;
var
  TD: TDBXTransaction;
begin
  TD := SQLConnection.BeginTransaction;
  try
    SQLConnection.ExecuteDirect('some sql command');
    SQLConnection.ExecuteDirect('some sql command');
    SQLConnection.CommitFreeAndNil(TD);
  except
    SQLConnection.RollbackFreeAndNil(TD);
  end;
end;

This exception is being raised to the user, so I assume it's raised by RollbackFreeAndNil, since all rest is inside a try..except.

Should I wrap RollbackFreeAndNil with another try..except? What a mess.

I'm using Delphi 2009, DBX with Firebird 2.1 and Devart's driver.

+3  A: 

What would happen if CommitFreeAndNil threw an exception?

RollbackFreeAndNil would be called. Would TD be valid then?

You're eating the exception, and hence the evidence. Don't do that; re-throw:

procedure BlaBla;
var
  TD: TDBXTransaction;
begin
  TD := SQLConnection.BeginTransaction;
  try
    SQLConnection.ExecuteDirect('some sql command');
    SQLConnection.ExecuteDirect('some sql command');
  except
    SQLConnection.RollbackFreeAndNil(TD);
    raise;
  end;
  SQLConnection.CommitFreeAndNil(TD);
end;
Craig Stuntz
And when re-throwing, you could use the new inner-exception-feature, as shown by Jim McKeeth at CodeRage III.
Vegar
Thanks Craig, please, read again my question because I added more information after you answer.
Erick Sasse
See code example.
Craig Stuntz
Thanks, this will help to investigate the problem.
Erick Sasse
The problem was not related to my try..except block.
Erick Sasse
My first sentence: "What would happen if CommitFreeAndNil threw an exception?" Your solution: "And then I get the exception of invalid transaction object." Yup, completely unrelated!
Craig Stuntz
A: 

The problem is that SQLConnection.BeginTransaction returns nil if SQLConnection is not Connected to the database. And then I get the exception of invalid transaction object.

I never expected that. It should try to connect or raise an exception. Returning nil doesn't make sense to me.

Erick Sasse
A: 

SQLConnection.DBXConnection.BeginTransaction(TDBXIsolations.ReadCommitted);

Adelson