How to detect overflow when convert string to integer in java

前端 未结 3 1785
一生所求
一生所求 2021-01-12 04:02

if I want to convert a string into an int in java do you know if there is a way for me to detect overflow? by that I mean the string literal actually represents a value whic

3条回答
  •  难免孤独
    2021-01-12 04:28

    If I want to convert a string into an int in java do you know if there is a way for me to detect overflow?

    Yes. Catching parse exceptions would be the correct approach, but the difficulty here is that Integer.parseInt(String s) throws a NumberFormatException for any parse error, including overflow. You can verify by looking at the Java source code in the JDK's src.zip file. Luckily, there exists a constructor BigInteger(String s) that will throw identical parse exceptions, except for range limitation ones, because BigIntegers have no bounds. We can use this knowledge to trap the overflow case:

    /**
     * Provides the same functionality as Integer.parseInt(String s), but throws
     * a custom exception for out-of-range inputs.
     */
    int parseIntWithOverflow(String s) throws Exception {
        int result = 0;
        try {
            result = Integer.parseInt(s);
        } catch (Exception e) {
            try {
                new BigInteger(s);
            } catch (Exception e1) {
                throw e; // re-throw, this was a formatting problem
            }
            // We're here iff s represents a valid integer that's outside
            // of java.lang.Integer range. Consider using custom exception type.
            throw new NumberFormatException("Input is outside of Integer range!");
        }
        // the input parsed no problem
        return result;
    }
    

    If you really need to customize this for only inputs exceeding Integer.MAX_VALUE, you can do that just before throwing the custom exception, by using @Sergej's suggestion. If above is overkill and you don't need to isolate the overflow case, just suppress the exception by catching it:

    int result = 0;
    try {
        result = Integer.parseInt(s);
    } catch (NumberFormatException e) {
        // act accordingly
    }
    

提交回复
热议问题