简体   繁体   中英

hex string to Integer parsing exception handling in java

I need to parse string hex value to the Integer value. Like this:

String hex = "2A"; //The answer is 42  
int intValue = Integer.parseInt(hex, 16);

But when I insert an incorrect hex value (for example "LL") then I get java.lang.NumberFormatException: For input string: "LL" How I can avoid it (for example return 0)?

Enclose it in a try catch block. That is how Exception Handling works: -

int intValue = 0;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    System.out.println("Invalid Hex Value");
    // intValue will contain 0 only from the default value assignment.
}

For input string: "LL" How I can avoid it (for example return 0)?

Just catch the exception and assign zero to intvalue

int intValue;
try {
String hex = "2A"; //The answer is 42  
intValue = Integer.parseInt(hex, 16);
}
catch(NumberFormatException ex){
  System.out.println("Wrong Input"); // just to be more expressive
 invalue=0;
}

You can catch the exception and return zero instead.

public static int parseHexInt(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

However, I recommend re-evaluating your approach, as 0 is a valid hex number as well, and doesn't signify invalid input such as "LL" .

How I can avoid it (for example return 0)

Using a simple method which will return 0 in case a NumberFormatException occurrs

public int getHexValue(String hex){

    int result = 0;

    try {
        result = Integer.parseInt(hex, 16);
     } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return result;
}

Just catch the exception and set the default value. However, you need to declare the variable outside the try block.

int intValue;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    intValue = 0;
}

If you need to set the value using an initializer expression (say, for a final variable), you'll have to package up the logic in a method:

public int parseHex(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

// elsewhere...
final int intValue = parseHex(hex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM