Why doesn't a Java constant divided by zero produce compile time error? [duplicate]

时光毁灭记忆、已成空白 提交于 2019-11-26 20:57:19

问题


Possible Duplicate:
Is 1/0 a legal Java expression?

Why does this code compile?

class Compiles {
    public final static int A = 7/0;
    public final static int B = 10*3;

    public static void main(String[] args) {}
}

If I take a look in the compiled class file, I can see that B has been evaluated to 30, and that A still is 7/0.

As far as I understand the JSL an expression where you divide by zero is not a constant.

Ref: JLS 15.28

My above statement is due to this line:

A compile-time constant expression is an expression denoting a value of primitive type

Hence dividing by zero is not evaluated to a primitive value.

What I really dont understand is why the compiler allows this anyway? Just to be clear, my code above crashes runtime with a "java.lang.ExceptionInInitializerError"

As it seems to me the compiler threats any final static variable as a constant and evaluates it compile time. That means that the compiler already has tried to evaluate A, but since it was a division by zero it just let it go through. No compile time error. But this seems very very bizarre... The compiler knows it is a divide by zero and that it will crash runtime but nevertheless it doesn't flag a compile error!

Can anyone explain to me why?


回答1:


To throw an java.lang.ExceptionInInitializerError is the only correct behavior.

If your code did not compile, a perfectly valid Java program would have been rejected, and that would have been a bug.

The only correct alternative to putting 7/0 in the compiled code, would actually be to explicitly throw a ExceptionInInitializerError, but how much more useful is that?

The compiler knows it is a divide by zero and that it will crash runtime but nevertheless it does flag a compile error!

Actually, I wouldn't agree with that... would this program crash?

class Compiles {
    public final static int A = 7/0;
    public final static int B = 10*3;

    public static void main(String[] args) {}

}

public class Test {

    // Application entry point.
    public static void main(String[] args) {
        try {
            new Compiles();

            launchTheMissiles();

        } catch (ExceptionInInitializerError e) {

            doUsefulStuff();

        }
    }
}



回答2:


JLS 15.28 Constant Expression:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

...

Therefore 7/0 is not a compile-time constant, since its evaluation completes abruptly due to division by zero. So, it's treated as a regular run-time expression, and throws an exception in runtime.



来源:https://stackoverflow.com/questions/4980360/why-doesnt-a-java-constant-divided-by-zero-produce-compile-time-error

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