Java – is it bad practice to capture numberformatexception?

I have to parse a string that can take hexadecimal or other non hexadecimal values

0xff, 0x31 or a, PC, label, etc

I use this code to split two situations:

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 hard to read? Are there other (perhaps more elegant) solutions?

Editor: I want to clarify (in my case) that a wrong input does not exist: I only need to distinguish whether it is a hexadecimal number, otherwise For completeness, I am making a simple assebler for dcpu-16

Solution

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

That is, if you want a simple and readable way to handle numberformatexceptions, you can consider using the numberutils class

Toint (string STR, int DefaultValue) method converts string to int. if the conversion fails, the default value is returned If the string is empty, the default value is returned

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

This method encapsulates exception capture and handling, as shown in the following source code Therefore, the client only needs 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;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>