How to Prevent Java.Lang.Numberformatexception: For Input String: "N/A"

How can I prevent java.lang.NumberFormatException: For input string: N/A?

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

  1. Exception Handling

    try{
    int i = Integer.parseInt(input);
    } catch(NumberFormatException ex){ // handle your exception
    ...
    }

or - Integer pattern matching -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
...
}

java.lang.NumberFormatException: For input string: 5.3

any other way we can handle this without try and catch?

You need to parse it with the right parse method so that the exception is not thrown.

value can be any thing.

Well if that is literally true, it means that you cannot parse it, except the most trivial sense.

it's not fixed that it will always be float.it can be integer and double too.

Ah ... so when you said "any thing" you didn't mean anything?

There are three possible ways to handle this:

  1. Just read the error code as a string, and don't attempt to parse it.

    Ask yourself: do you actually need to treat the error code as a number? What does that buy you? And what if the error code isn't a recognizable number at all? (Will your application be able to cope?)

  2. Parse the error code using parseDouble, and represent it as a double. The syntax parsed by parseDouble is the same as for parseFloat and a superset of what is accepted by parseInt. Specifically, parseDouble will happily parse an integer value ... and give you the double representation of that integer.

    The downside is that for large enough integers, the double representation will be imprecise / inaccurate. Depending on the actual code values, this might cause problems.

  3. If you must parse it with the right type then the way you avoid try / catch would be to use Pattern to implement regexes to test which of the expected formats the error code is in. Then call the corresponding parseXXX method to parse it.

    The downside is that you now need three (or more) different variables with types int, float, double and so on to represent the parsed error code values. And all of the places where you used the error code later in your application will have to deal with that.

  4. And of course, you could just use a sequence try-catches.



Related Topics



Leave a reply



Submit