我正在使用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
}
(如您所料,该doSomething()
方法会引发一些异常,并且返回的接口将比更为通用MyInterface
。)
Eclipse在最后一个return语句下划线强调为死代码,如果我按照快速修复建议将其删除,则会出现“此方法应返回String类型的结果”错误。
为什么最后一个return语句为死代码?是因为上课吗?假设它doSomething()
可能返回null,如果您将其强制转换,是否会抛出类强制转换异常?
而且,为什么Eclipse为什么建议我用导致死代码警告的方式修复错误?是因为Eclipse无法预测这一点吗?
您发布的代码中没有无效代码。我能看到的唯一问题是在这里:
if (myVar != null) {
return myVar;
}
您要返回MyInterface
时应返回String
。编译器会抱怨它,这是正确的。
另外,作为更好的选择,您不应直接在try
orcatch
块内返回,而应在此块后设计单个位置以返回结果。这将使您的代码避免任何死代码编译器错误。您可能会看起来像:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句