Java – Hibernate, Spring, @Transactional – surround with try/catch


Im working on developing a webapplication with Spring 3 and Hibernate 3.6. Ive got some questions to the @Transactional Annotation and the structure of the code.

-> When I use @Transactional (transaction management with Spring), do I have to surround the @Transactional-annotated methods with try/catch when calling them?

For example, when I got a method which loads, changes and returns then an object and I call it from another class: do I have to surround the call with try/catch? maybe something goes wrong, no object is returned, database connection fails.. I dont know.

until now, I thought @Transactional cares for all possible occurring exceptions and rolls back every operation in this transaction when an error occurs.
but if it occurs, I must inform the user somehow. when I call the transactional-method in the try-block and it is rolled back, the catch block is activated?
I can tell then the user "something did go wrong". Otherwise the user maybe would not be informed?

Or is it sufficient to check if there is an object returned (if/else), then I dont need try/catch?
Im new and I would like to hear how other structure their code. Thank you 🙂

Best Solution

Handling exceptions in Spring is really easy with HandlerExceptionResolvers and @ExceptionHandlers. I tend to use @ExceptionHandler exclusively.

You can use an @ExceptionHandler to handle a specific exception instead of handling it yourself in a try-catch block.

If the user wanted a resource that wasn't found and you want to send a 404.

public void handleNotFoundException(NotFoundException exc) {
  // log something.

If there was a Server issue where you'd want to send a 500

public void handleException(SomeException exc, WebRequest request, HttpServletResponse response) {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Sorry dude, my server broke");

You also should narrowly handle the exceptions. In general you shouldn't do @ExceptionHandler(Exception.class) and I also believe that it works in order, so if you do handle the general Exception it should be the last method in the class.

Related Question