//溢出 short a = Short.MAX_VALUE; //溢出了但是没有异常 a += 1; System.out.println(String.format("a is %s",a));
我查了一些资料,有的说是出于性能考虑没有做溢出检测,有办法检测吗?
我知道在c#中可以通过checked关键字来设置,不知道java中是否有类似的机制
长风秋雁
浏览 686回答 1
1回答
慕码人2483693
public static short checkAndAdd(short a, short b) {if (Short.MAX_VALUE - a < b) {throw new ArithmeticException("Overflow");}return (short)(a + b);}apache 的 common math 包有类似的方法