Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Inside a @Transactional method you catch an exception and want the transaction to roll back without rethrowing. How do you do it?

Call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() inside the catch block: the method then returns normally, and when the proxy tries to commit it sees the flag and rolls back instead. With TransactionTemplate, call status.setRollbackOnly() on the TransactionStatus passed into the callback. Rethrowing an unchecked exception is usually clearer, and the one thing we must not do is swallow the exception without marking rollback, because then the partial work commits.

Why this question is asked

Sometimes a method must handle a failure itself, for example to return an error result to the caller instead of an exception, and still undo whatever it wrote before the failure. This is where a common bug appears: the developer catches the exception, logs it, returns a result, and the half-finished data commits. Interviewers ask this short coding question to check that we know Spring's transaction status can be controlled directly, and that we know when not to. In this answer, we will see the bug, fix it with setRollbackOnly() in declarative and programmatic code, look at what happens inside Spring, and compare it with rethrowing.

1The Bug: Swallowing the Exception

Here is a method that imports two parts of an order and returns a result object instead of throwing. When the second part fails, the first part is committed.

Java
@Transactional
public ImportResult importOrder(OrderFile f) {
try {
orders.save(f.header()); // INSERT order
lines.saveAll(f.lines()); // throws DataIntegrityViolationException
return ImportResult.ok();
} catch (DataIntegrityViolationException e) {
log.warn("import failed", e);
return ImportResult.failed(e.getMessage());
}
}
// The method returns normally, so the proxy COMMITS: the order header is saved without lines

From Spring's point of view, nothing went wrong: the method returned a value, so the transaction interceptor committed. The interceptor only decides about rollback when an exception leaves the method through the proxy.

2Fix: Mark the Transaction Rollback-Only

Spring exposes the status of the current declarative transaction through TransactionAspectSupport. Calling setRollbackOnly() on it sets a flag that the commit step checks.

Java
@Transactional
public ImportResult importOrder(OrderFile f) {
try {
orders.save(f.header());
lines.saveAll(f.lines());
return ImportResult.ok();
} catch (DataIntegrityViolationException e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
log.warn("import failed, rolling back", e);
return ImportResult.failed(e.getMessage());
}
}
// The method returns normally, the proxy sees rollback-only: ROLLBACK, nothing saved
// The caller receives ImportResult.failed(...) and no exception
Step throughWhat the proxy does at the end of the method
  1. Did an exception leave the method?
    YesApply rollback rulesNoGo on
  2. Is the status marked rollback-only?
    YesRoll back quietlyNoCommit

2 steps in order. Play them, or step through them one at a time.

Without setRollbackOnly(), a caught exception leads straight to a commit.

Notice that the caller does not get an UnexpectedRollbackException here. Because this method started the transaction and marked it itself, Spring treats the rollback as intended and rolls back quietly. currentTransactionStatus() throws NoTransactionException if it is called where no declarative transaction is active, so it only belongs inside a @Transactional method reached through the proxy.

3The Same Thing With TransactionTemplate

With programmatic transactions, the callback receives the TransactionStatus directly, so we mark it there. The template then rolls back when the callback returns.

Java
ImportResult result = transactionTemplate.execute(status -> {
try {
orders.save(f.header());
lines.saveAll(f.lines());
return ImportResult.ok();
} catch (DataIntegrityViolationException e) {
status.setRollbackOnly(); // template rolls back after the callback
return ImportResult.failed(e.getMessage());
}
});
// result: failed(...), database unchanged

This version is often easier to read, because the status object is right there and the transaction boundary is visible in the code.

4A Catch With Joined Transactions

If importOrder() is called from another @Transactional method, it joins that outer transaction with REQUIRED. Marking rollback-only then marks the shared transaction, so the whole outer unit of work will roll back, and the outer method, which did not mark anything itself, gets UnexpectedRollbackException when it tries to commit. That is correct behaviour, since part of its work failed, but it surprises people. If the import must fail alone, it needs its own transaction, for example REQUIRES_NEW, or the caller must check the result and decide.

5Why Rethrowing Is Usually Clearer

setRollbackOnly() couples our business code to Spring's transaction API and hides the rollback inside a catch block, where readers may miss it. In most cases, letting an unchecked exception propagate, or catching and rethrowing a domain exception, is clearer: the rollback happens through the normal rule, the caller sees the failure, and the code reads as 'this failed'.

Java
@Transactional
public void importOrder(OrderFile f) {
try {
orders.save(f.header());
lines.saveAll(f.lines());
} catch (DataIntegrityViolationException e) {
throw new ImportFailedException(f.name(), e); // unchecked: rollback, caller informed
}
}

If the caller needs a result object, a cleaner design is often to let the transactional method throw and have the non-transactional caller, such as a controller or a batch step, catch it and build the result. Then the transaction boundary and the error handling stay in separate places, and setRollbackOnly() is kept for the rare case where the method itself must return normally.

6Follow-up questions

Does setRollbackOnly() stop the method?

No. It only sets a flag; the method keeps running and any further writes still execute against the database, then they are all rolled back at the end. Usually we return right after setting it.

Is there a way to roll back part of the work?

Within one transaction, only with a savepoint (NESTED propagation or status.createSavepoint() with JDBC), which does not work for JPA operations in general. Otherwise the independent part needs its own transaction.

What happens if we mark rollback-only and then throw a checked exception?

The transaction still rolls back. The rollback rules only decide whether an exception causes a rollback; they cannot undo a rollback-only mark that is already set.

7Conclusion

In this answer, we saw that catching an exception inside a @Transactional method makes the proxy commit, because no exception left the method. We fixed it with TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(), or status.setRollbackOnly() in a TransactionTemplate callback, which makes the commit step roll back quietly. We also saw that in a joined transaction the mark affects the whole outer unit, and that rethrowing an unchecked exception is usually the clearer choice.

What to say in the interviewAbout 80 seconds aloud

Open with

If I catch the exception and return normally, the transaction interceptor commits, because it only rolls back when an exception leaves the method through the proxy, and any partial work is saved.

Then, if they want more

To roll back without rethrowing, I call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() in the catch block. That sets a flag on the current transaction; the method keeps running, so I usually return right after, and when the proxy tries to commit it sees the flag and rolls back.

Because the method started and marked the transaction itself, it's a quiet rollback, the caller gets my result object and no exception. With TransactionTemplate it's the same idea but simpler: the callback gets the TransactionStatus, and I call status.setRollbackOnly() on it.

One catch is joined transactions: if my method was called inside an outer transaction, the mark applies to the whole shared transaction, and the outer method will get UnexpectedRollbackException when it commits.

Having said that, I'd normally prefer to rethrow an unchecked exception, maybe wrapped in a domain exception, because the rollback then follows the normal rules, the failure is visible to the caller, and the code doesn't depend on Spring's transaction API. setRollbackOnly is for the rare case where the method really has to return normally.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Inside a @Transactional method you catch an exception and want the transaction to roll...": https://scrivio-interview-library.netlify.app/databases/transactions/a64b65f73b/