My getChoice()
method takes a char input from the console and returns the char to main()
.
Should getChoice()
just throw the exception and let main()
deal with it:
static char getChoice() throws IOException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
return (char)br.read();
}
Or should getChoice()
catch the exception, deal with it and return a char:
static char getChoice()
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
char temp;
try {
temp = (char)br.read();
} catch(IOException exc) {
System.out.println("Invalid Input");
temp = (char)0;
}
return temp;
}
Which approach is better from the designing perspective? Is there a better way to do this?
Throwing an exception seems like the better option to me, since returning a default value (or error code, if you like) in case of an exception does not let the caller know there was an error while reading the input from the user. Using a return value like (char)0 as an error code brings you back to languages that don't have exception handling.
That said, you should consider catching the IOException
and throwing some exception of your own, that describes the error.
For example :
static char getChoice() throws UserInputException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
char temp = (char)0;
try {
temp = (char)br.read();
}
catch (IOException ioEx) {
throw new UserInputException ("Error reading input", ioEx);
}
return temp;
}