Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

commit() and rollback() in a finally block

 
Jean Fore
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, according to the Java coding conventions, isn't it appropriate to use the commit() or rollback() in a finally block? Please see the following code which is a portion of my program. Please let me know is it appropriate.

finally {
try {
if (dbConnection != null) {
if (errorFound) {
dbConnection.rollback();
} else {
dbConnection.commit();
}
dbConnection.close();
dbConnection = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}

Thanks
-JEAN
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64715
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved to the JDBC forum.
 
Mattias Arthursson
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your code you risk leaving the connection hanging if any exception is encountered during commit() or rollback(). I'd probably put the rollback() in the catch block and the commit() last in the original try block, like so:
 
Jean Fore
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for the response. Now I understand the flow of how to do this!
-JEAN
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic