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:
String userdata = /*value from gui*/
int val;
try
{
val = Integer.parseInt(userdata);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentinel
val = Integer.MIN_VALUE;
}
I could use a regex to check if it's parseable, but that seems like a lot of overhead as well.
What's the best practice for handling this situation?
EDIT: Rationale:
There's been a lot of talk on SO about exception handling, and the general attitude is that exceptions should be used for unexpected scenarios only. However, I think bad user input is EXPECTED, not rare. Yes, it really is an academic point.
Further Edits:
Some of the answers demonstrate exactly what is wrong with SO. You ignore the question being asked, and answer another question that has nothing to do with it. The question isn't asking about transition between layers. The question isn't asking what to return if the number is un-parseable. For all you know, val = Integer.MIN_VALUE; is exactly the right option for the application that this completely context free code snippet was take from.
question from:
https://stackoverflow.com/questions/174502/string-to-int-in-java-likely-bad-data-need-to-avoid-exceptions 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…