eivamu
eivamu

Reputation: 3225

Removing dead code leads to error

I'm using Eclipse 4.3 Kepler (actually STS 3.6.1).

I ran into some code:

private String someMethod(String myParam) {
    try {
        MyInterface myVar = (MyInterface) domeSomething(myParam);
        if (myVar != null) {
            return myVar.methodThatReturnsString();
        }
    } catch (Exception e) {
        return "";
    }
    return ""; // eclipse marks this as dead code
}

(As you'd expect, the doSomething() method throws some exception, and it returns an interface more general than MyInterface.)

Eclipse underlines the last return statement as dead code, and if I remove it as the quickfix suggests, I and up with the "This method should return a result of type String" error.

Why is the last return statement dead code? Is it because of the class cast? Say that doSomething() could return null, if you cast it, would that throw a class cast exception?

And, why does Eclipse suggest that I fix the error with something that leads to a dead code warning? Is it because Eclipse can't predict this?

Upvotes: 1

Views: 1132

Answers (2)

Seelenvirtuose
Seelenvirtuose

Reputation: 20648

You are most likely using Eclipse's annotation org.eclipse.jdt.annotation.NonNull on the method domeSomething.

In that case, the Eclipse compiler knows, that the variable does not refer to null and thus the code will either return the variable (BTW: This is another compiler error, as the variable is not of type String) or throw an exception which will return the empty string. The last line is then indeed dead code. Hence, the warning.

However, removing that last line leads to code that does not comply with the JLS. Hence, the compiler error.

Upvotes: 2

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

There's no dead code in your posted code. The only problem I can see is here:

if (myVar != null) {
    return myVar;
}

You're returning a MyInterface when you should return a String. The compiler will complain about it and it's right.

Also, as a better alternative, you should not directly return inside the try or catch block, instead design a single place after this block to return the result. This will make your code avoid any dead code compiler error. Your could should look like:

private String someMethod(String myParam) {
    String result = "";
    try {
        MyInterface myVar = (MyInterface) domeSomething(myParam);
        if (myVar != null) {
            result = myVar.methodThatReturnsString();
        }
    } catch (Exception e) {
        //handle the exception
        //basic handling shown
        System.out.println("Warning. There was a problem executing someMethod:");
        e.printStacktrace();
    }
    return result;
}

Upvotes: 6

Related Questions