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

前端 未结 16 1999
迷失自我
迷失自我 2020-12-04 18:02

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:

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 18:27

    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.

提交回复
热议问题