Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I'm running into this situation where I need to parse a String into an int and I don't know what to do with the NumberFormatException. The compiler doesn't complain when I don't catch it, but I just want to make sure that I'm handling this situation properly.

private int getCurrentPieceAsInt() {
    int i = 0;
    try {
        i = Integer.parseInt(this.getCurrentPiece());
    } catch (NumberFormatException e) {
        i = 0;
    }
    return i;
}

I want to just simplify my code like this. The compiler doesn't have a problem with it, but the thread dies on the NumberFormatException.

private int getCurrentPieceAsInt() {
    int i = 0;
    i = Integer.parseInt(this.getCurrentPiece());
    return i;
}

Google CodePro wants me to log the exception in some way, and I agree that this is best practice.

private int getCurrentPieceAsInt() {
    int i = 0;
    try {
        i = Integer.parseInt(this.getCurrentPiece());
    } catch (NumberFormatException e) {
        i = 0;
        e.printStackTrace();
    }
    return i;
}

I want this method to return 0 when the current piece is not a number or cannot be parsed. When I don't catch the NumberFormatException explicitly, does it not assign the variable i? Or is there some default value that Integer.parseInt() returns?

General style says that if I catch an exception, I should log it somewhere. I don't want to log it. It's normal operation for this exception to be thrown sometimes, which also doesn't sit well with me. I cannot find a function, however, which will tell me if Integer.parseInt() will throw an exception. So my only course of action seems to be to just call it and catch the exception.

The javadoc for parseInt doesn't help much.

Here are the specific questions I'd like to know:

  • 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.
  • 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.
  • 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".
like image 917
Erick Robertson Avatar asked Dec 10 '10 15:12

Erick Robertson


People also ask

Is NumberFormatException checked or unchecked?

The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java.

How do you handle number format exceptions in Python?

How to handle NumberFormatException. Use try and catch block surrounding the code that can cause NumberFormatException. ) Another way of handling the exception is the use of throws keyword.

Which of the following statement will cause a NumberFormatException?

The NumberFormatException is actually thrown by the parseXXX() functions when functions are not able to convert or format(convert ) a string into numeric value like integer, float, double etc., because of the format of an input string is illegal and not appropriate.


2 Answers

  • 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;
    }
}
like image 79
Cameron Skinner Avatar answered Oct 14 '22 13:10

Cameron Skinner


There is NumberUtils.toInt(String, int) in commons lang which will do exactly what you want.

NumberUtils.toInt("123", 42) ==> 123
NumberUtils.toInt("abc", 42) ==> 42
like image 29
daveb Avatar answered Oct 14 '22 13:10

daveb