这在使用 Java SE 7 实现更好的资源管理:超越语法糖中或多或少地得到了解释。以这个片段为例:
try(
FileInputStream fin = new FileInputStream(input);
FileOutputStream fout = new FileOutputStream(output);
GZIPOutputStream out = new GZIPOutputStream(fout)
) {
// ... do work
}
这将等同于以下内容:
FileInputStream localFileInputStream = new FileInputStream(paramString1);
Object localObject1 = null;
try {
FileOutputStream localFileOutputStream = new FileOutputStream(paramString2);
Object localObject2 = null;
try {
GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localFileOutputStream);
Object localObject3 = null;
try {
// ... do work
} catch (Throwable localThrowable6) {
localObject3 = localThrowable6;
throw localThrowable6;
} finally {
if (localGZIPOutputStream != null) {
if (localObject3 != null) {
try {
localGZIPOutputStream.close();
} catch (Throwable localThrowable7) {
localObject3.addSuppressed(localThrowable7);
}
} else {
localGZIPOutputStream.close();
}
}
}
} catch (Throwable localThrowable4) {
localObject2 = localThrowable4;
throw localThrowable4;
} finally {
if (localFileOutputStream != null) {
if (localObject2 != null) {
try {
localFileOutputStream.close();
} catch (Throwable localThrowable8) {
localObject2.addSuppressed(localThrowable8);
}
} else {
localFileOutputStream.close();
}
}
}
} catch (Throwable localThrowable2) {
localObject1 = localThrowable2;
throw localThrowable2;
} finally {
if (localFileInputStream != null) {
if (localObject1 != null) {
try {
localFileInputStream.close();
} catch (Throwable localThrowable9) {
localObject1.addSuppressed(localThrowable9);
}
} else {
localFileInputStream.close();
}
}
}
}
是的,那是一大堆代码,但正如您所见,它将每个try
-with-resources 块嵌套在上面的块中。