First of all, there is no rollback of an exception, it’s a rollback of a transaction.
- If you throw your exception with
@ApplicationException(rollback=true)
, you don’t have to rollback the transaction manually.Context.setRollbackOnly()
forces the container to rollback the transaction, also if there is no exception. - A checked exception itself doesn’t rollback a transaction. It needs to have the annotation
@ApplicationException(rollback=true)
. If the exception is aRuntimeException
and the exception isn’t caught, it forces the container to rollback the transaction. But watch out, the container will in this case discard the EJB instance. - As mentioned in 2.), if you throw a
RuntimeException
, the transaction will be rolled back automatically. If you catch an checked exception inside the code, you have to usesetRollbackOnly
to rollback the transaction.
For further information, check out the free book Mastering EJB. It describes the rollback scenarios very well and is free for download.