Is 1/0 a legal Java expression?

前端 未结 8 1211
萌比男神i
萌比男神i 2020-11-27 16:47

The following compiles fine in my Eclipse:

final int j = 1/0;
// compiles fine!!!
// throws ArithmeticException: / by zero at run-time

Java

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 17:47

    It's legal because no where is it a given that the compiler is supposed to fold constant expressions at compile time.

    A "smart" compiler might compile:

    a = 1 + 2
    

    as

    a = 3
    

    But there's nothing that says the compiler HAS to do that. Other than that, 1/0 is a legal expression just like:

    int a;
    int b;
    
    a = a/b;
    

    is a legal expression.

    At RUNTIME it throws an exception, but that's a runtime error for a reason.

提交回复
热议问题