Common underflow and overflow exceptions

余生长醉 提交于 2019-11-26 21:32:41

问题


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

  1. How are they different from each other?
  2. What are the subclasses of these exceptions?
  3. In which scenario they are thrown?
  4. Which of them can be handled and how?
  5. What are the best practice related to them?

Any link to useful tutorial will do


回答1:


Okay, the OP talked about wanting to know about both stack overflow and arithmetic overflow, as well as their corresponding underflow. Here goes....

  1. Arithmetic overflow happens when a number gets too big to fit in its value type. For example, an 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.
  2. Arithmetic underflow happens when a floating point number gets too small to distinguish very well from zero (the precision of the number got truncated). In Java, these do not cause an exception either.
  3. Stack overflow happens when you call a function, that calls another function, that then calls another, then another...and the function call stack gets too deep. You get a StackOverflowError when that happens.
  4. Stack underflow doesn't happen in Java. Its runtime system is supposed to prevent that sort of stuff from happening.

To answer the OP's other question (see comments), when you overstep the boundaries of an array, an IndexOutOfBoundsException is issued.




回答2:


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:

double d1 = 100 / 0.;
if (Double.isNaN(d1)) {
    throw new RuntimeException("d1 is not a number");
}
if (Double.isInfinite(d1)) {
    throw new RuntimeException("d1 is infinite");
}

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.




回答3:


Java has no unsigned integers. This makes it easy to throw an Exception, if you think it might be useful.

public class Counter
{
  private int counter = 0;

  public int increment ()
  {
    counter += 1;
    if (counter < 0)
      throw new RuntimeException ("Counter overflow");
    else
      return counter;
  }

  public String toString() { return String.valueOf(counter); }
}


来源:https://stackoverflow.com/questions/2154712/common-underflow-and-overflow-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!