常见的下溢和溢出异常
我试图掌握java中的溢出和下溢异常,但无法获得任何好的教程。具体来说,我想了解
- 它们有何不同?
- 这些异常的子类是什么?
- 它们在什么情况下被抛出?
- 其中哪些可以处理以及如何处理?
- 与它们相关的最佳实践是什么?
任何有用教程的链接都可以
I am trying to get a hold of overflow and underflow exceptions in java, but couldn't get any nice tutorial. Specifically I wish to learn
- How are they different from each other?
- What are the subclasses of these exceptions?
- In which scenario they are thrown?
- Which of them can be handled and how?
- What are the best practice related to them?
Any link to useful tutorial will do
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,OP 谈到想要了解堆栈溢出和算术溢出,以及它们相应的下溢。 。
int
保存的值介于 -231 和 231-1(含)之间。如果您的号码超过这些限制,则会发生溢出,并且号码会“环绕”。这些不会导致 Java 中生成异常。为了回答OP的其他问题(请参阅评论),当您超出数组的边界时,会发出
IndexOutOfBoundsException
。Okay, the OP talked about wanting to know about both stack overflow and arithmetic overflow, as well as their corresponding underflow. Here goes....
int
holds values between -231 and 231-1, inclusive. If your number goes over these limits, an overflow occurs, and the number "wraps around". These do not cause an exception to be generated in Java.StackOverflowError
when that happens.To answer the OP's other question (see comments), when you overstep the boundaries of an array, an
IndexOutOfBoundsException
is issued.在 Java 算术中,上溢或下溢将永远抛出异常。相反,对于浮点算术,该值设置为
不是数字
、“无限”或零。要测试这些,您可以使用静态方法: isNaN 或 isInfinite 使用适当的包装类。您可以酌情处理。示例:
对于某些操作,您可以获得 ArithmeticException,例如在整数数学中
除以零
时。我刚刚问了一个关于处理此问题的完整项目风格方法的相关问题。
In Java arithmetic, overflow or underflow will never throw an Exception. Instead, for floating point arithmetic the value is set as
Not a number
, 'infinite' or zero.To test for these you can use the static methods: isNaN or isInfinite using the appropriate wrapper classes. You can handle this as appropriate. Example:
For certain operations you can get an ArithmeticException, for example when
dividing by zero
in Integer maths.I just asked a related question about a complete project style way to handle this.
Java 没有无符号整数。如果您认为这可能有用的话,这使得抛出异常变得容易。
Java has no unsigned integers. This makes it easy to throw an Exception, if you think it might be useful.
由于这是一个非常老的问题,需要注意的是,从 Java 8 开始,Math 包提供了“精确”的算术方法,当发生溢出时会触发异常。
例如
将触发 java.lang.ArithmeticException: integer Overflow 。
Since this is a very old question, it should be noted that since Java 8, the Math package provides "exact" arithmetic methods which will trigger exceptions when overflow occurs.
e.g.
will trigger java.lang.ArithmeticException: integer overflow .