What is the proper way to handle a NumberFormatException when it is expected?

  • Is there a method that I can call that will tell me if Integer.parseInt() will throw a NumberFormatException before calling it? Then I would have no problem logging this, since it should never happen.

Sadly, no. At least not in the core Java API. It’s easy to write one, however – just modify the code below.

  • If I simply do not catch the exception, will the valiable not get assigned? Then I will simply initialize it to the value that I want when it’s not a number and not catch the exception.

If you do not catch the exception then the stack will unwind until it hits a catch block that will handle it, or it will unwind completely and halt the thread. The variable will, in fact, not be assigned but this is not exactly what you want.

  • Is there a way to mark the exception somehow explicitly that I don’t care about it? I’m thinking this would be something similar to AWTEvent.consume(). If so, then I will do this so that Google CodePro doesn’t see this as “unlogged”.

There may be a way to tell CodePro to ignore this particular warning. Certainly with tools like FindBugs and Checkstyle you can turn off warnings in specific locations. (EDIT: @Andy has pointed out how to do this.)

I suspect what you want is something like the Commons lang package mentioned by @daveb. It’s pretty easy to write such a function:

int parseWithDefault(String s, int def) {
    try {
        return Integer.parseInt(s);
    }
    catch (NumberFormatException e) {
        // It's OK to ignore "e" here because returning a default value is the documented behaviour on invalid input.
        return def;
    }
}

Leave a Comment