Search code examples
javanumberformatexception

Catching the NumberFormatException


Below is the class somebody else wrote.

The problem that I am facing is that when it get's into the parse method with null as the rawString, it is throwing NumberFormatException.

So what I was thinking to do is, I should catch that NumberFormatException and set the value itself as null. So the way I did is right?

public class ByteAttr {

    @JExType(sequence = 1)
    private Byte value;

    public static ByteAttr parse(String rawString) {
        ByteAttr attr = new ByteAttr();
        try {
            attr.setValue(Byte.valueOf(rawString));
        } catch (NumberFormatException nfEx) {
            attr.setValue(null);
        }
        return attr;
    }

    public Byte getValue() {
        return this.value;
    }

    public void setValue(Byte value) {
        this.value = value;
    }
}

Solution

  • The correct approach depends on what you want to accomplish in the program.

    • If it makes sense for ByteAttr.getValue() to return null later in your program, then your approach could work.
    • However, you need to consider whether you should be throwing an exception if parse is called with an indecipherable argument (including null). An alternative is to catch the NumberFormatException and throw a different exception that has semantic meaning in your program.
        public static ByteAttr parse(String rawString) throws BadAttributeException {
            ByteAttr attr = new ByteAttr();
            try {
                attr.setValue(Byte.valueOf(rawString));
            } catch (NumberFormatException nfEx) {
                throw new BadAttributeException(nfEx); // wrap original exception
            }
            return attr;
        }
    
    • Another technique is to pass a default value to parse for those cases when rawString is indecipherable:
        public static ByteAttr parse(String rawString, Byte defaultValue) {
            ByteAttr attr = new ByteAttr();
            try {
                attr.setValue(Byte.valueOf(rawString));
            } catch (NumberFormatException nfEx) {
                attr.setValue(default);
            }
            return attr;
        }