Reviewing Java Exception Hierarchy Through a JDBC Transaction Pitfall

Problem While writing a JDBC transaction example, I intended to test that uncommitted data is rolled back and verify this using assertThat to ensure the test works correctly. However, the rollback didn’t occur, and the transaction was committed even though exception was thrown, causing an issue.

<Logic>




<Test Code>

<Test Result>


<Solution (SQLException -> Exception)>



Brief explanation

Upon investigating, I found that the logic itself was fine, but the try-catch block was catching only SQLException, failing to catch IllegalStateException. As a result, the rollback was not called, and the code proceeded to the finally block, where the release method was invoked, setting auto-commit back to true. This prompted me to review Java’s exception on hierarchy again.

Detail about the problem

So, what exactly was the problem? IllegalStateException is a subclass of RuntimeException, which is not related to SQLException in the exception hierarchy. Therefore, SQLException couldn’t catch IllegalStateException. To resolve this, I caught Exception, the parent class of both SQLException and RuntimeException, thereby solving the issue.


Comments

Popular posts from this blog

@ModelAttribute vs @RequestBody in Validation

Side Project(a self-imposed 3-day "Hackathon" challenge)

Google: The King is Back