0

I have a try-catch-finally block that looks like so:

ResultSet rs;
PreparedStatement ps;
Connection conn;
try {
    for (int i = 0; i < list.size(); i++) {
        ** execute SQL query **
    }
} catch (Exception e) {
    throw e;
} finally {
    ** close result set **
    ** close prepared statement **
    ** close connection **
}

I've verified that my ArrayList list had 534 elements in it. The problem is that the finally block to close everything is executing after the first occurrence of my for loop which causes the next occurrence to throw an exception because the connection is now closed.

I've never encountered a situation where the finally block executes before the try block has completed. What could cause this scenario?

Mike
  • 269
  • 3
  • 8
  • 20

2 Answers2

2

Basically, what is happening is that finally is working as expected. The short explanation is that a finally block is executed no matter how the try block terminates.

In your example, and based on what you have said, the most likely scenario is as follows:

  • the loop body throws some exception,
  • the exception is caught and rethrown, and
  • the finally block is then executed.

The finally block will NOT be executed before the try block "terminates", so your theory that the finally block is causing the loop body to fail is not correct.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Without more source I would guess that you are not committing your transaction.

If you switch your connection to not auto-commit and then forget to commit your transaction it may seem like your finally block is executing before your queries when in fact they are merely awaiting committal before executing.

See here for a discussion.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213