java 溢出的数字转换,如何在java中将字符串转换为整数时检测溢出

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 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..

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值