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?
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;
}