It is difficult to find consensus, although many say that you should not use exceptions to handle incorrect user input . However, I am not sure if this is bad in my particular case. Could you explain why I am wrong?
My code (please focus only on the aspect of exception handling). My rational use of exceptions here is that if I hadn’t done this, assuming that I want the validation logic to be close to parsing keywords (since parsing and validation are closely related), I would have to change three methods (submitOnAdd , submitOnUpdate, getKeywords) to get them to handle this exception. Do you think I'm definitely wrong in this case to use exceptions, or is it a personal style issue?
public SubmitResponse internalSubmit(Map<String, String[]> submitParameters) {
try {
if (!submitParameters.containsKey("foo")) {
return submitOnAdd(submitParameters);
} else {
return submitOnModify(submitParameters);
}
} catch (SubmitErrorException e) {
return SubmitResponse.fieldError(Arrays.asList(e.getSubmitError()));
}
}
SubmitResponse submitOnAdd(Map<String, String[]> submitParamters) {
if (addKeywordList(createKeywordList(submitParameters.get("concatenated_keywords"))
return SubmitResponse.OK();
return SubmitResponse.bad("Failed to add");
}
SubmitResponse submitOnUpdate(Map<String, String[]> submitParamters) {
if (updateKeywordList(createKeywordList(submitParameters.get("concatenated_keywords"))
return SubmitResponse.OK();
return SubmitResponse.bad("Failed to update");
}
List<Keyword> getKeywords(String concatenatedKeywords) {
List<String> rawKeywords = splitKeywords(concatenatedKeywords);
return Collections.transform(new Function<String, Keyword>() {
@Override
public KeywordListProto.Keyword apply(String expression) {
return buildKeyword(expression);
}
});
}
private Keyword buildKeyword(String rawKeyword) {
if ()
throw new SubmitResponseException("Failed to parse keyword " + rawKeyword);
return parsedKeyword;
}
source
share