I have this:
try(Transaction t = sess.beginTransaction()){
// do something with t...
} catch (Exception e) { // abort transaction if something goes wrong
...
t.rollback();
t.close();
}
However, t is not in scope of the catch block. I reviewed this here try/catch scope in Java/C#.
Declaring t before the try-catch-block doesn´t work, as the syntax in try requires the variable to be declared right there.
Is there any way that I can initialize t like this, and still make sure that the transaction gets closed / rollbacked? Or should I just begin the transaction before the try/catch-block?
EDIT: Transaction is an 'AutoClosable'. Does this mean I don't need to explicitly handle rollback and closing?
CodePudding user response:
try to initialize Transaction t as default before the try, it might work
CodePudding user response:
"how can I access transaction declared in try-header in catch blocks?"
You can't. Using "try-with-resources" is convenient in many scenarios, but not intended to allow accessing the underlying resource (database transaction) within the try
block.
Instead, if you want to have direct control over the resource, you would need to do code like below. It's different from your approach in that it isn't using the automatic "try-with-resources" statement. Also, note that the t.close()
is in the finally
block (not the catch
block) - you should always try to close the transaction, whether or not an exception was thrown.
Transaction t = session.beginTransaction();
try {
t.run("...");
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
t.close();
}
Further, according to docs, if your catch
block were to run in your try-with-resources attempt, the resource (your transaction) would have already been closed prior to running the code in the catch block:
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Above is from https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html, which includes other detail and examples.