iteye_19575 2010-01-06 16:32
浏览 238
已采纳

j2se源码部分阅读疑问

我看到以下代码,对API中处理int类型的最小值Integer.MIN_VALUE用NumberFormatException捕获异常的方式来处理感到无法理解.
请高手们给予解释.怎么能用捕获异常的方式来处理这个边界值.这个有违设计理念吧?
[code="java"] public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;

    // Handle minus sign, if present
    if (nm.startsWith("-")) {
        negative = true;
        index++;
    }

    // Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
    index += 2;
        radix = 16;
}
else if (nm.startsWith("#", index)) {
    index ++;
        radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
    index ++;
        radix = 8;
}

    if (nm.startsWith("-", index))
        throw new NumberFormatException("Negative sign in wrong position");

    try {
        result = Integer.valueOf(nm.substring(index), radix);
        result = negative ? new Integer(-result.intValue()) : result;
    } catch (NumberFormatException e) {
        // If number is Integer.MIN_VALUE, we'll end up here. The next line
        // handles this case, and causes any genuine format error to be
        // rethrown.
        String constant = negative ? new String("-" + nm.substring(index))
                                   : nm.substring(index);
        result = Integer.valueOf(constant, radix);
    }
    return result;
}[/code]

[b]问题补充:[/b]
我的意思是...为什么要用捕获异常的方式来解决这个问题.而不是在方法内部直接判断.

  • 写回答

3条回答 默认 最新

  • bx~liu 2010-01-11 22:38
    关注

    我的理解是这种情况很少出现(指解析-(2^31)),单为这个数写个判断在绝大多数情况下没有必要,反而影响性能,用异常来处理更合理。
    异常就应该处理很少出现的情况

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名