Eclipse. Why don't I see compile error if method with unreachable code doesn't invoke?

纵饮孤独 提交于 2019-12-23 20:14:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!