问题
I noticed that if method with unreachable code doesn't invoke - then this code compiles by eclipse compiler and executes.
Demonstration:
import java.io.FileNotFoundException;
class R3 {
public void g(){
try {
} catch (FileNotFoundException e) {//any checked exception
}
}
public static void main(String [] args) {
System.out.println("23");
new R3().g();
}
}
result:
Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body
and compare it with following code:
import java.io.FileNotFoundException;
class R3 {
public void g(){
try {
} catch (FileNotFoundException e) {//any checked exception
}
}
public static void main(String [] args) {
System.out.println("23");
//new R3().g();
}
}
compiles and executes normally.
Is it eclipse compiler optimization or is it normal behaviour?
回答1:
This could contribute to the discussion. When I compiled this with eclipse and THEN decompiled it online, this is what I got. For some reason Eclipse decides to compile your method to throw a runtime error that there was an unresolved compilation problem? Interesting.
class R3
{
public void g()
{
throw new Error("Unresolved compilation problem: \n\tUnreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body\n");
}
public static void main(String[] args)
{
System.out.println("23");
}
}
I found this somewhere else on SO, but it explains what happens pretty clearly.
One notable difference is that the Eclipse compiler lets you run code that didn't actually properly compile. If the block of code with the error is never ran, your program will run fine. Otherwise it will throw an exception indicating that you tried to run code that doesn't compile.
来源:https://stackoverflow.com/questions/22614515/eclipse-why-dont-i-see-compile-error-if-method-with-unreachable-code-doesnt-i