logoalt Hacker News

Okxtoday at 4:29 PM1 replyview on HN

The code:

  public int parseOrDefault(String value, int defaultValue) {
      if (value == null || value.isBlank()) return defaultValue;
      for (int i = 0; i < value.length(); i++) {
          char c = value.charAt(i);
          if (i == 0 && c == '-') continue;
          if (!Character.isDigit(c)) return defaultValue;
      }
      return Integer.parseInt(value);
  }
Is probably worse than Integer.parseInt alone, since it can still throw NumberFormatExceptions for values that overflow (which is no longer handled!). Would maybe fix that. Unfortunately this is a major flaw in the Java standard library; parsing numbers shouldn't throw expensive exceptions.

Replies

deepsuntoday at 7:17 PM

And it will fail with "-"