eiv*_*amu 1 java eclipse dead-code spring-tool-suite eclipse-kepler
我正在使用Eclipse 4.3 Kepler(实际上是STS 3.6.1).
我碰到了一些代码:
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
}
Run Code Online (Sandbox Code Playgroud)
(正如您所期望的那样,该doSomething()方法会抛出一些异常,并返回一个比一般更通用的接口MyInterface.)
Eclipse将最后一个return语句强调为死代码,如果我将其删除为quickfix建议,我将使用"此方法应返回String类型的结果"错误.
为什么最后一个return语句是死代码?是因为班级演员吗?假设doSomething()可以返回null,如果你施放它,会抛出一个类强制转换异常吗?
而且,为什么Eclipse建议我用导致死代码警告的错误修复错误?是因为Eclipse无法预测这个吗?
您发布的代码中没有死代码.我能看到的唯一问题是:
if (myVar != null) {
return myVar;
}
Run Code Online (Sandbox Code Playgroud)
你返回MyInterface时,你应该返回String.编译器会抱怨它,这是正确的.
此外,作为更好的替代方案,您不应该直接返回try或catch阻止,而是在此块之后设计一个位置以返回结果.这将使您的代码避免任何死代码编译器错误.你应该看起来像:
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;
}
Run Code Online (Sandbox Code Playgroud)