Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 486
gstackoverflow Avatar asked Feb 10 '26 17:02

gstackoverflow


1 Answers

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.

like image 65
Tristan Avatar answered Feb 12 '26 06:02

Tristan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!