G
gtcc2009
Suppose I have this code:
public void batchWork () throws BusinessProcessException {
try {
conn.setAutoCommit(false);
performUpdate1();
performUpdate2();
conn.commit();
} catch (SQLException sqle) {
try {conn.rollback();} catch (SQLException sqle2) {}
throw sqle;
}
}
The problem is that if performUpdate1() throws an unchecked exception
(say NullPointerException), then the catch (SQLException sqle) won't be
executed, thus no rollback() is called, and some JDBC drivers will
perform commit in the case a connection is closed with a pending
transaction (neither committed or rollbacked). As a result, the action
done in performUpdate1() is commited, while performUpdated2() is not,
which breaks the purpose of transaction.
Moreover, because the signature of the method is
BusinessProcessException, I cannot catch a Throwable, rollback, then
simply rethrow. Instead, I have to wrap Throwable into
BusinessProcessException and throw it. However it's a very bad coding
practice to "eat" unchecked exception like that.
Is there any workaround for this?
public void batchWork () throws BusinessProcessException {
try {
conn.setAutoCommit(false);
performUpdate1();
performUpdate2();
conn.commit();
} catch (SQLException sqle) {
try {conn.rollback();} catch (SQLException sqle2) {}
throw sqle;
}
}
The problem is that if performUpdate1() throws an unchecked exception
(say NullPointerException), then the catch (SQLException sqle) won't be
executed, thus no rollback() is called, and some JDBC drivers will
perform commit in the case a connection is closed with a pending
transaction (neither committed or rollbacked). As a result, the action
done in performUpdate1() is commited, while performUpdated2() is not,
which breaks the purpose of transaction.
Moreover, because the signature of the method is
BusinessProcessException, I cannot catch a Throwable, rollback, then
simply rethrow. Instead, I have to wrap Throwable into
BusinessProcessException and throw it. However it's a very bad coding
practice to "eat" unchecked exception like that.
Is there any workaround for this?