如何在java中将字符串转换为整数时检测溢出 [英] How to detect overflow when convert string to integer in java

查看:971
本文介绍了如何在java中将字符串转换为整数时检测溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在java
中将字符串转换为int,你知道我是否有办法检测溢出?
我的意思是字符串文字实际上代表一个大于MAX_INT的值?

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 which is larger than MAX_INT?

java doc没有提到它..
it只是说如果字符串不能被解析为整数,它将通过FormatException
没有提到关于溢出的一个词。

java doc didn't mention it.. it just says that if the string can not be parsed as an integer, it will through FormatException didn't mention a word about overflow..

推荐答案


如果我想在java中将字符串转换为int,你知道我是否有办法检测溢出?

是的。捕获解析异常将是正确的方法,但这里的难点是 Integer.parseInt(String s) 抛出 NumberFormatException for 任何解析错误,包括溢出。您可以通过查看JDK的 src.zip 文件中的Java源代码进行验证。幸运的是,存在一个构造函数 BigInteger(String s) 将抛出相同的解析异常,之外的范围限制异常,因为 BigInteger s没有界限。我们可以使用这些知识来捕获溢出情况:

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;
}

如果你真的需要为仅定制输入超过Integer.MAX_VALUE,你可以在抛出自定义异常之前,使用@ Sergej的建议。如果上面是过度杀戮并且您不需要隔离溢出的情况,只需通过捕获它来抑制异常:

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
}

这篇关于如何在java中将字符串转换为整数时检测溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆