在数字溢出时抛出异常 [英] Throw exception on numeric overflow

查看:135
本文介绍了在数字溢出时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当发生整数溢出而不是静默失败时,是否有可能抛出某种运行时异常。例如。

Is it possible to throw some sort of runtime exception when integer overflow occurs rather then failing silently. For e.g.

int x = 100000000 * 1000000000;

打印 1569325056 由于溢出而我我想要获得某种运行时异常

print 1569325056 due to overflow and what I w'd like is to get some sort of runtime exception

推荐答案

是的,从Java-8开始你可以使用新的< a href =https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-int-int->完全方法,会抛出异常溢出时出现(java.lang.ArithmeticException:整数溢出)。例如,

Yes, Starting from Java-8 you can use the new Exact method, it will throw an exception(java.lang.ArithmeticException: integer overflow) on overflow. E.g.

Math.multiplyExact(100000000, 1000000000);

这篇关于在数字溢出时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆