Transactions and Try/Catch

  • Thread starter Thread starter Jonathan Wood
  • Start date Start date
J

Jonathan Wood

I've been unable to find any information on this:

If I create a SqlTransaction object with a using block, is calling Rollback
completely necessary if an exception occurs? It's hard to imagine that an
error that causes the using block to exit before encountering a Commit would
result in anything other than a rollback.

I know Rollback is preferred, but calling it from catch is a bit dicey. For
one thing, if I create the transaction object in a using block, then it
won't be available in a catch statement outside of that block. And for
another thing, I'd need another try/catch to handle any errors if the
Rollback fails.

Thanks for any tips.

Jonathan
 
Hi Jonathan,

No, you don't need to.
Rollback is called internally within Dispose method if Commit wasn't
called - that's the whole point of using "using": it makes sure you either
commit or rollback in timely fashion.
You can call Rollback earlier if you wish to.
 
Thanks Miha. That makes perfect sense to me. I guess this is documented
somewhere but I had trouble finding it.

Jonathan

Miha Markic said:
Hi Jonathan,

No, you don't need to.
Rollback is called internally within Dispose method if Commit wasn't
called - that's the whole point of using "using": it makes sure you either
commit or rollback in timely fashion.
You can call Rollback earlier if you wish to.

--
Miha Markic [MVP C#, INETA Country Leader for Slovenia]
RightHand .NET consulting & development www.rthand.com
Blog: blog.rthand.com

Jonathan Wood said:
I've been unable to find any information on this:

If I create a SqlTransaction object with a using block, is calling
Rollback completely necessary if an exception occurs? It's hard to
imagine that an error that causes the using block to exit before
encountering a Commit would result in anything other than a rollback.

I know Rollback is preferred, but calling it from catch is a bit dicey.
For one thing, if I create the transaction object in a using block, then
it won't be available in a catch statement outside of that block. And for
another thing, I'd need another try/catch to handle any errors if the
Rollback fails.

Thanks for any tips.

Jonathan
 
Back
Top