Search code examples
javaparsingexceptionnumberformatexception

Is catching NumberFormatException a bad practice?


I have to parse a String that can assume hex values or other non-hex values

0xff, 0x31 or A, PC, label, and so on.

I use this code to divide the two cases:

String input = readInput();

try {
    int hex = Integer.decode(input);            
    // use hex ...

} catch (NumberFormatException e) {
   // input is not a hex, continue parsing
}

Can this code be considered "ugly" or difficult to read? Are there other (maybe more elegant) solutions?

EDIT : I want to clarify that (in my case) a wrong input doesn't exist: i just need to distinguish if it is a hex number, or not. And just for completeness, i'm making a simple assebler for DCPU-16.


Solution

  • Exception handling is an integral part (and one of the design goals) of the Java programming language... you shouldn't cast them off just because you think they are "ugly".

    That said, if you want a simple and readable way to handle NumberFormatExceptions, you might consider using the NumberUtils class instead.

    The toInt(String str, int defaultValue) method converts a String to an int, returning a default value if the conversion fails. If the string is null, the default value is returned.

     NumberUtils.toInt(null, 1) = 1
     NumberUtils.toInt("", 1)   = 1
     NumberUtils.toInt("1", 0)  = 1
    

    The method encapsulates exception catching and handling, as seen in the source code below. As a result, the client only needs to make a single method call.

    public static int toInt(String str, int defaultValue) {         
        if(str == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }