java7中的新概念,try后面加括号,括号内可以写是使用的资源(创造对象)。
effective java建议,使用try-with-resources代替try-finally
比较能代表这个功能的是下列代码
public static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
}
}
并不是所有的对象都可以在try后的括号内创建,该对象要实现AutoCloseable接口,如,我测试建立的类HHH
public class HHH implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("hhhh");
throw new BusinessException("123");
}
public void hhh() {
System.out.println("ttthhh");
throw new BusinessException("567");
}
}
其实只看这个,不是很理解到底是如何实现的,那就直接看反编译的class就行了(Idea就是好)
Test代码
public static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
}
}
public static void testHHH() throws Exception {
try (HHH h = new HHH()) {
h.hhh();
}
}
反编译后的代码
public static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
Throwable var3 = null;
try {
OutputStream out = new FileOutputStream(dst);
Throwable var5 = null;
try {
byte[] buff = new byte[1024];
int n;
while((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (Throwable var29) {
var5 = var29;
throw var29;
} finally {
if (out != null) {
if (var5 != null) {
try {
out.close();
} catch (Throwable var28) {
var5.addSuppressed(var28);
}
} else {
out.close();
}
}
}
} catch (Throwable var31) {
var3 = var31;
throw var31;
} finally {
if (in != null) {
if (var3 != null) {
try {
in.close();
} catch (Throwable var27) {
var3.addSuppressed(var27);
}
} else {
in.close();
}
}
}
}
public static void testHHH() throws Exception {
HHH h = new HHH();
Throwable var1 = null;
try {
h.hhh();
} catch (Throwable var10) {
var1 = var10;
throw var10;
} finally {
if (h != null) {
if (var1 != null) {
try {
h.close();
} catch (Throwable var9) {
var1.addSuppressed(var9);
}
} else {
h.close();
}
}
}
}
使用try-with-resources的目的,也是要保证资源的关闭(继承的AutoCloseable接口有close()抽象方法),即使关闭失败,也要成功返回异常