Java 8 では算術オーバーフローを検出可能となるよっておはなしです。
Math クラスに算術オーバーフローを検出できるメソッドが追加されました。
ちょっとしたサンプルプログラムをのせておきます。
package jp.yucchi.exact;
/**
*
* @author Yucchi
*/
public class Exact {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE - 1);
try {
System.out.println(Math.addExact(Integer.MAX_VALUE, 1));
} catch (ArithmeticException ae) {
// G'catch! :p
ae.printStackTrace();
}
try {
System.out.println(Math.subtractExact(Integer.MIN_VALUE, 1));
} catch (ArithmeticException ae) {
// G'catch! :p
ae.printStackTrace();
}
}
}
実行結果は次の通りになります。
-2147483648
2147483647
java.lang.ArithmeticException: integer overflow
at java.lang.Math.addExact(Math.java:790)
at jp.yucchi.exact.Exact.main(Exact.java:14)
java.lang.ArithmeticException: integer overflow
at java.lang.Math.subtractExact(Math.java:829)
at jp.yucchi.exact.Exact.main(Exact.java:20)
この他にも Java 8 で追加された便利なものがありますので興味のある方は API ドキュメントに目を通してみるといいですよ!
Hatena タグ: Java