Why negative size of array is not a compilation error but throws java.lang.NegativeArraySizeException

落花浮王杯 提交于 2020-05-14 22:06:24

问题


java does not allow to initialize an array with negative size. For example:

int[] arr = new int[-1];

If this is already known, why it throws NegativeArraySizeException instead of compilation error? Just curious to know why java decides it to be thrown at runtime while it is known at compile time that it will fail.


回答1:


This check could be performed at compile time only in situations when the size is specified as a constant expression. However, Java Language Specification requires this check to be done at run time:

15.10.2 Run-Time Evaluation of Array Creation Expressions

At run time, evaluation of an array creation expression behaves as follows:

[...]

  • First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.
  • Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then a NegativeArraySizeException is thrown.

In deciding if a certain check should be performed at compile-time or not the compiler design team considers costs and benefits of the new feature. Since the compile-time check would not replace a run-time check, but would be performed in addition to it, the added benefit is marginal. It does not mean, however, that the feature should not be implemented in a future version of the compiler, only that the language designers did not prioritize it high enough to be implemented now.



来源:https://stackoverflow.com/questions/49009638/why-negative-size-of-array-is-not-a-compilation-error-but-throws-java-lang-negat

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