我经常发现在调试程序时,在代码块中插入一个return语句很方便(虽然可以说是不好的做法).我可能会在Java中尝试这样的东西....
class Test {
public static void main(String args[]) {
System.out.println("hello world");
return;
System.out.println("i think this line might cause a problem");
}
}
Run Code Online (Sandbox Code Playgroud)
当然,这会产生编译器错误.
Test.java:7:无法访问的语句
我可以理解为什么警告可能是合理的,因为使用未使用的代码是不好的做法.但我不明白为什么这需要产生错误.
这只是Java试图成为一个保姆,还是有充分的理由使这成为编译器错误?
为什么这段代码没有给出"无法访问的代码"错误?由于布尔值只能为true或false.
public static void main(String args[]) {
boolean a = false;
if (a == true) {
} else if (a == false) {
} else {
int c = 0;
c = c + 1;
}
}
Run Code Online (Sandbox Code Playgroud) 我在Eclipse中尝试了以下内容:
if (false) {}
:警告'死码'while (false) {}
:编译错误'无法访问的代码'我想知道这种差异是否存在真正的"原因".我已经发现了......
...但为什么不允许while (false)
相同的调试目的?
假设我在Java类中有以下行,
System.out.println("start");
if(true)//The compiler will give compile time error if I uncomment this.
throw new RuntimeException();
System.out.println("end");
Run Code Online (Sandbox Code Playgroud)
如果if(true)
被注释,将出现无法访问的代码错误消息.为什么编译器不知道下面的行if(true)
总会被执行?
Java编译器是设计为这样工作还是限制?