I am throwing an exception from a controller, like below
try {
if (formValidationResult.size() > 0) {
validationResults.put(errorMsg, formValidationResult);
}
} catch (Exception exception) {
LOGGER.error("Error while performing validation in FormController -->"
+ exception.getMessage());
throw new ServiceException(exception.getMessage());
}
if (validationResults.size() > 0) {
throw new ValidationFailureException(validationResults,"Validation Error");
}
Here i am getting a validation error;
com.ge.dbt.common.exception.ValidationFailureException: Validation
Error
Can I include a catch block to catch the ValidationFailureException here?
Assuming that validationResult and formValidationResult are collections, I don’t see why there is a need to enclose the call to the size and put methods in a try catch block? What exception are you expecting anyway while checking the size of these collections or inserting a new value anyway?
I can’t give you the code because I am typing from my phone but this is what you can do :
Indicate that the method containing your code throws a ValidationFailureException in the method signature.
Remove the try catch block you have presented and remove the if block that checks whether validationResult is non empty and the code inside the if block.
If formValidationResult is not empty, store the error message in validationResult and throw a ValidationFailureException.
That’s it. Clean and simple. No need for any try-catch blocks and no need to separately check if validationResult is not empty before throwing a ValidationFailureException.