好奇 if 条件和异常

Curious about if condition and exception

当我使用下面的代码时,发生编译错误。

try {
        throw new Exception("Exceptionist");
        System.out.println("another line"); //compilation error
}catch (Exception e) {
        System.out.println("Exception:" + e.getMessage());
}

编译错误的原因是抛出异常后无法编写代码。 但是当我尝试这样的事情时

try {
        if (true)
            throw new Exception("Exceptionist"); 
        System.out.println("another line"); // no compilation
} catch (Exception e) {
        System.out.println("Exception:" + e.getMessage());
}

即使 Eclipse IDE 预测 syso 为死代码,为什么不 java 指出它。即使它被编译成字节码,syso 也永远不会被执行。那么为什么不将其视为编译错误。 (我知道这不是编译错误 :| 。可能是其他表示方式。)它是由程序员选择的吗?

解释在Java Language Specification:

It is a compile-time error if a statement cannot be executed because it is unreachable.

[...]

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

所以,即使编译器确实可以从字节码中删除 if (true) 因为 true 是一个常量表达式,它仍然认为 if 之后的代码是可访问的,因为它假设这个if 块用于出于调试原因有条件地执行一些代码。您必须能够将常量表达式从 false 更改为 true,反之亦然,并且不能修改代码中的任何其他内容以使其编译。