Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

parsing - String to Int in java - Likely bad data, need to avoid exceptions

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.

Might also be useful (depending on the application) to log the bad input so you can trace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...