为什么Java常量除以零会产生编译时错误? [英] Why doesn't a Java constant divided by zero produce compile time error?

查看:210
本文介绍了为什么Java常量除以零会产生编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

1/0是合法的Java表达式吗?

为什么这段代码会编译?

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) {}
}

如果我查看已编译的类文件,我可以看到B已经被评估为30,而A仍然是7/0。

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.

据我了解JSL,除以零的表达式不是常数。

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

参考: 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.

我真正不理解的是为什么编译器无论如何允许这个?为了清楚起见,上面的代码使用java.lang.ExceptionInInitializerError崩溃运行时

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"

在我看来,编译器威胁任何最终的静态变量为常量评估编译时间。这意味着编译器已经尝试评估A,但由于它是零除以它只是让它通过。没有编译时错误。但这看起来非常奇怪...编译器知道它是一个除以零并且它会崩溃运行时但是它不会标记编译错误!

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?

推荐答案

java.lang.ExceptionInInitializerError 是唯一正确的行为。

如果你的代码没有编译,那么一个完全有效的Java程序会被拒绝,这本来就是一个错误。

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

放置 7/0的唯一正确选择在编译的代码中,实际上是显式抛出一个 ExceptionInInitializerError ,但是它有多大用处呢?

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?


编译器知道它除以零并且它会崩溃运行时但是它确实标记了编译错误!

实际上,我不同意......这个程序会崩溃吗?

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();

        }
    }
}

这篇关于为什么Java常量除以零会产生编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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