Struggling still with this after hours or research.. I have a simple helper class which is my first foray into try/catch error handling. I want to know if an input is valid against the type required and ask for a new input if it isn’t… simple or so I thought. The class is being used in a simple term deposit calculator and is called multiple times (i.e. initial deposit, interest rate etc).
Here is the offending class, if this isn’t sufficient to resolve I’ll post up some additional snippets.
private Float inFloat;
private String temp;
private int inInt;
private String inString;
BufferedReader in = null;
boolean validInput = false;
public Float getFloat(String prompt) {
validInput = false;
do {
try {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
temp = in.readLine();
inFloat = Float.valueOf(temp);
validInput = true;
} catch (IOException e) {
System.out.println("Please enter a valid float value");
} finally {
try {
if (in != null) {
in.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
} while (validInput == false);
return inFloat;
}
Update – Fixed!!!
Thanks for the quick feedback… I managed to find another post that mentioned I shouldn’t be closing off the BufferedReader and came up with the following adjustments so it now works. I’m now catching a NumberFormatException as well.. thanks for the tip 🙂
Not sure why it works now that I don’t close off the BufferedReader… but I’ll take the result!!
private Float inFloat;
private String temp;
private int inInt;
private String inString;
BufferedReader in = null;
boolean validInput = false;
public Float getFloat(String prompt) {
validInput = false;
do {
try {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
temp = in.readLine();
inFloat = Float.valueOf(temp);
validInput = true;
} catch (NumberFormatException e) {
System.out.println("Please enter a valid float value");
} catch (IOException e) {
e.printStackTrace();
}
} while (validInput == false);
return inFloat;
}
Float.valueOf(String s)will throw aNumberFormatExceptionif it can’t parse the input. Catch that one in addition toIOException.In your code,
NumberFormatExceptionis thrown (if the input is invalid) but not catched inside the method, so the method will return immediatly after completing thefinallyblock.