I am trying to create a Response class in Java which has a method
void setResponse(String response);
Different response subclasses will have different requirements for the response. The string that is passed to the function is received from the user.
What is the correct way of handling a wrong response?
- Should the function throw an exception like IllegalResponseException
- Should the function be declared like
boolean setResponse(String response, String errorMsg)
and return false if the response is wrong and set the error message to the appropriate value
Edit:
I want to design the UI so that I keep prompting the user for a response until a correct one is entered.
This depends somewhat on what you want the program to do when incorrect response is set.
If it’s a 100% critical thing and the program should never proceed in such a case, throw an exception.
If it needs to be handled correctly by the caller and continue execution of the program, you can do either one, but I personally prefer #2. Why?
A great discussion of exceptions for error handling is here – it does not directly address exceptions vs. return codes but a very clear list of downsides of criticisms of checked exceptions applies to this discussion as well (again, this is assuming the error you’re handling is not a super-critical one which should cause program termination, in which case an unchecked exception is proper).