Friday, January 19, 2007

JDBC transaction rollback

We are advised to rollback a JDBC transaction in the catch block that handles SQLException, just as shown in the code below. But what if a runtime exception is thrown while after midway in the transaction? Control will never go to the catch block and the transaction will never be rolled back.

There are two ways to handle this issue. The first is to explicitly set a flag in this class if the transaction commits. In the finally block we should check the flag. If it has not been set, it means that the transaction could not be commited and must be rolled back. Another way is to catch 'Exception' after 'SQLException'. If a runtime exception is thrown we will handle it in the catch block by rolling back the transaction and rethrowing the RuntimeException.

What do you think? Is this a workable solution? Which os the two approaches would you favor?

2 comments:

A third option would be to always do a rollback in the finally block - doing a rollback after doing commit doesn't change anything. I guess there is some sort of performance issue to consider but I doubt it's significant.