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

前端 未结 16 2116
迷失自我
迷失自我 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:28

    I'm sure it is bad form, but I have a set of static methods on a Utilities class that do things like Utilities.tryParseInt(String value) which returns 0 if the String is unparseable and Utilities.tryParseInt(String value, int defaultValue) which allows you to specify a value to use if parseInt() throws an exception.

    I believe there are times when returning a known value on bad input is perfectly acceptable. A very contrived example: you ask the user for a date in the format YYYYMMDD and they give you bad input. It may be perfectly acceptable to do something like Utilities.tryParseInt(date, 19000101) or Utilities.tryParseInt(date, 29991231); depending on the program requirements.

提交回复
热议问题