Seeing as Java doesn\'t have nullable types, nor does it have a TryParse(), how do you handle input validation without throwing an exceptions?
The usual way:
The exception mechanism is valuable, as it is the only way to get a status indicator in combination with a response value. Furthermore, the status indicator is standardized. If there is an error you get an exception. That way you don't have to think of an error indicator yourself. The controversy is not so much with exceptions, but with Checked Exceptions (e.g. the ones you have to catch or declare).
Personally I feel you picked one of the examples where exceptions are really valuable. It is a common problem the user enters the wrong value, and typically you will need to get back to the user for the correct value. You normally don't revert to the default value if you ask the user; that gives the user the impression his input matters.
If you do not want to deal with the exception, just wrap it in a RuntimeException (or derived class) and it will allow you to ignore the exception in your code (and kill your application when it occurs; that's fine too sometimes).
Some examples on how I would handle NumberFormat exceptions: In web app configuration data:
loadCertainProperty(String propVal) {
try
{
val = Integer.parseInt(userdata);
return val;
}
catch (NumberFormatException nfe)
{ // RuntimeException need not be declared
throw new RuntimeException("Property certainProperty in your configuration is expected to be " +
" an integer, but was '" + propVal + "'. Please correct your " +
"configuration and start again");
// After starting an enterprise application the sysadmin should always check availability
// and can now correct the property value
}
}
In a GUI:
public int askValue() {
// TODO add opt-out button; see Swing docs for standard dialog handling
boolean valueOk = false;
while(!valueOk) {
try {
String val = dialog("Please enter integer value for FOO");
val = Integer.parseInt(userdata);
return val;
} catch (NumberFormatException nfe) {
// Ignoring this; I don't care how many typo's the customer makes
}
}
}
In a web form: return the form to the user with a usefull error message and a chance to correct. Most frameworks offer a standardized way of validation.