Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

Exception Handling with @Transactional


Question:

If an exception occurs inside a method annotated with @Transactional, what type of exception handling behavior will occur?


Will the transaction rollback for:

1: Checked exceptions?

2: Unchecked exceptions?


Please explain.

If an exception occurs inside a method annotated with @Transactional:

1: Unchecked exceptions (like RuntimeException and Error) - The transaction will automatically rollback.

2: Checked exceptions (like Exception but not RuntimeException) - By default, the transaction will NOT rollback.


Simple way to remember:

1: Rollback happens for unchecked exceptions.

2: No rollback for checked exceptions unless you specify it manually with rollbackFor in @Transactional.


Example:

@Transactional(rollbackFor = Exception.class)


This will make the transaction rollback for checked exceptions too.

Ready for commit