0
BoomeH
8y

What do you think, is this bad practise?

boolean isNumber = true;
try {
Integer.parseInt(somestring);
} catch (NumberFormattingException e) {
isNumber = false;
}

Or is it better to create a method to check, even though I only use it at one place in 700 lines of code?

Comments
  • 0
    The question is: How often do you think it is NOT a number.

    Practices asside, handling exceptions and building traces in java is a VERY expensive operation.

    If this is generally a (you know) exception to your application then I would consider this fine. If not then I would use parsers and sanity checks to prevent this exception from happening.
  • 1
    @ChappIO Okay, thanks, didn't think about it being a costly operation. I'm adding data to an excel file, and one in every 18 columns is a number, the rest alphabetic strings. But it's 2500 rows, which means it's 17cols*2500rows exceptions thrown. Guessing I should build a method lol
  • 0
    @BoomeH Are they straight intergers? Then a very cheap way would be to check every character using isDigit.

    https://docs.oracle.com/javase/7/...
  • 0
    @ChappIO Yes that's my thinking aswell. They are between 1 to 20, so I'm guessing I could do somestring.toCharArray(), then for-loop each char and check if they all are digits, if yes, I just parse the whole string (since the parsed value won't surpass the integer max value).. Does that sound good or is there a more efficient way?
  • 0
    @BoomeH Yea sounds great.

    And ends up pretty clean like

    if(isNumber(input)) {
    Integer.par.....
    }
  • 1
    If this is actually an exception then it is no problem, but this looks like an attempt to handle control flow via exceptions which is terrible practice IMHO.
Add Comment