当if参数为true时,为什么在if else情况下java程序不会出错。为什么不异常(exception)。例如,这里的method1和method2即使有不可达的语句也不会发生任何(编译)错误,而method3会导致编译错误。
首先,请仔细阅读代码并提供答案。
public int method1() {
if(true) {
return 1;
} else {
return 2;//unreachable statement but doesn't make exception
}
}
public int method2() {
if(true) {
return 1;
} else if (true) {
return 2;//unreachable statement but doesn't make exception
} else {
return 3;//unreachable statement but doesn't make exception
}
}
public int method3() {
if(true) {
return 1;
} else if (true) {
return 2;//unreachable statement but doesn't make exception
} else {
return 3;//unreachable statement but doesn't make exception
}
return 3;//unreachable statement but makes exception
}
Java不支持严格的编译吗?这个问题背后的原理是什么?
最佳答案
该语言通过对if-then-else进行特殊处理来允许conditional compilation。这使得在编译时打开或关闭代码块变得容易。
从Java Language Specification's section on unreachable statements:
As an example, the following statement results in a compile-time error:
while (false) { x=3; }
because the statement x=3; is not reachable; but the superficially similar case:
if (false) { x=3; }
does not result in a compile-time error.
和:
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.