我看到以下代码,对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]
我的意思是...为什么要用捕获异常的方式来解决这个问题.而不是在方法内部直接判断.