gpt4 book ai didi

java - 好奇 if 条件和异常

转载 作者:行者123 更新时间:2023-11-29 05:08:48 26 4
gpt4 key购买 nike

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

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 block 出于调试原因有条件地执行某些代码。您必须能够将常量表达式从 false 更改为 true,反之亦然,并且不能修改代码中的任何其他内容以使其编译。

关于java - 好奇 if 条件和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29455007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com