Question

I am facing a very peculiar situation. I am using hibernate template with spring 3.0.5 for DB operations. When I try to insert a User model the first time, a DataAccessException is thrown, which I catch. Now I wish to retry the same DB operation for say 3 times. The second time when it, no exception is thrown.

Here is the code:

package com.user.profile.dao;

@Repository("userProfileDAOImpl")
public class UserProfileDAOImpl implements IUserProfileDAO {

@Autowired
private HibernateTemplate hibernateTemplate;

public Long insertUserProfileData(User user) throws AppNonFatalException {
Long id = null;
int retryCount = 0;

while (retryCount < 3) {
try {
id = (Long)hibernateTemplate.save(user);
}
catch (DataAccessException e) {
e.printStackTrace();
retryCount++;
System.out.println("Retry Count = " + retryCount); 
if (retryCount > 3) {
throw new AppNonFatalException(e.getLocalizedMessage(), "10000", e.getMessage(), e);
} 
}
catch (Exception e) {
/* not coming inside this block too second time onwards */
System.out.println("Pure Exception");
}
}

return id;
}

}

I read that RuntimeExceptions should not be caught. Then how do I retry the operation. Should I retry at the service layer? Am I missing something? Any help is appreciated.

Was it helpful?

Solution

From https://community.oracle.com/docs/DOC-983543:

Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code.

Since DataAccessException is a RuntimeException, you might want to check what is the real cause of the exception and fix it instead of catching it and retry the operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top