The following code causes Eclipse to display a dead code warning although the code is reachable. Am I missing something here, or is this an Eclipse/javac bug?
import java.util.ArrayList;
public class DeadCodeDemo {
public static class SomeClosable implements AutoCloseable {
@Override
public void close() throws Exception {
}
}
public static ArrayList<String> throwRuntime() {
throw new RuntimeException();
}
public static void main(String[] args) {
ArrayList<String> list = null;
try {
try (SomeClosable c = new SomeClosable()) {
list = throwRuntime();
}
try (SomeClosable c = new SomeClosable()) {
list.clear();
}
} catch (Exception e) {
if (list != null) { // Warning: Redundant null check: The variable list cannot be null at this location
System.out.println("List is not null");
} else {
System.out.println("List is null"); // Warning: Dead code
}
}
}
}
The code prints List is null
I'm using Eclipse 4.7.3a (Oxygen.3a) and JDK 8_162
list.clear()
and the message disappears. Also you can indeed replace theArrayList<String>
with any class and do the same (just call any method on it) and the warning is shown. Remove the method call and it works. – Timmielist.clear()
removing the warning: it's because Eclipse thinks "list has already been derefenced before, so it can't benull
or it would have thrown an NPE"; I've noticed that before. – Tomasine