For example, I have a method
void process(String userId) {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
try {
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
IlligalArgumentExceptionis the unchecked exceptionUserNotFoundExceptionis the unchecked exceptionAnalyticsAPIExceptionis the checked exception
I read that it is a best practice to start the method from try and finish with a catch instead of multiplying try-catch blocks in the one method.
Prefer exceptions to error codes We prefer exceptions to error codes because they are more explicit. When dealing with try / catch, we should not add more logic in a function than the try / catch block, so that function does one thing: handle errors. Recommendation: don’t use nested try / catch.
Something like this:
void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
But it looks strange. I throw an exception inside of the try-catch block and hope that it won't be handled in the catch. I expect that it will be thrown upper to the service which called that method.
I can do next:
public void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = callApi(userId, user.getDob(), user.getFirstName());
//logic
}
private DataResponse callApi(String userId, Date dob, String firstName){
try {
return analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
} catch(AnalyticsAPIException e) {
//logic
}
}
But it doesn't work always. So, what is the better?