Card 06/ 07
Practice: Predicting Whether a Transaction Rolls Back
A save followed by a checked payment exception: commit or rollback, and the one line that changes it.
@Transactional rolls back on unchecked exceptions and commits on checked ones, unless told otherwise. Apply that to the method below, and name the change that would reverse the outcome, before you open the answer. Give a short reason for each part of your answer.
A @Transactional method saves a row, then calls a payment gateway that throws PaymentDeclinedException, a checked exception, and does nothing else. Does the save roll back? What single change would alter the answer? And what happens if the gateway throws IllegalStateException instead?
See the answer
No, it commits. A checked exception does not roll back by default, so the saved row stays. Changing the annotation to @Transactional(rollbackFor = PaymentDeclinedException.class) makes it roll back instead.
Making PaymentDeclinedException extend RuntimeException would also reverse it, because the default rule then applies.
With IllegalStateException, which is unchecked, the save rolls back with no configuration at all: the default rule covers every RuntimeException.
← → move through sections and cards