我做了一些测试(使用Windows 7,Eclipse Juno 4.2.1和Java 7 SE),发现如果一个方法没有在catch-block中显式返回,并且如果对象是在try/catch之外声明的,则没有"资源"泄漏"警告已发出警告.
不会产生"资源泄漏":
public void extISImReturnNoWarning() {
InputStream is = null;
try {
is = new FileInputStream("A");
is.available();
} catch (IOException e) {
}
}
Run Code Online (Sandbox Code Playgroud)
代码中的小变化会导致"资源泄漏":
public void locISImReturnHasWarning() {
try {
InputStream is = new FileInputStream("A");
is.available();
} catch (IOException e) {
}
}
public void extISExReturnHasWarning() {
InputStream is = null;
try {
is = new FileInputStream("A");
is.available();
} catch (IOException e) {
return;
}
}
Run Code Online (Sandbox Code Playgroud)
所有方法看起来功能相同 - 那么解释是什么呢?如果这是一个错误,这是Eclipse还是Java问题?