Java7后try语句的优化
原始的写法先来看一段老代码 OutputStream out = null;
try {
out = response.getOutputStream()
} catch (IOException e1) {
e.printStackTrace();
}finally{
try {
if(out != null){
out.close();
}
} catch (IOException e2) {
e.printStackTrace();
}
}
这个输出流使用了try/catch/finally,写法繁琐,并且在关闭的时候也有可能会抛出异常,异常e2 会覆盖掉异常e1 。 ? 优化后的写法Java7提供了一种try-with-resource机制,新增自动释放资源接口AutoCloseable 在JDK7中只要实现了AutoCloseable或Closeable接口的类或接口,都可以使用try-with-resource来实现异常处理和资源关闭异常抛出顺序。异常的抛出顺序与之前的不一样,是先声明的资源后关闭。 上例中OutputStream实现了Closeable接口,可以修改成: try(OutputStream out = response.getOutputStream()) {
//
} catch (IOException e) {
e.printStackTrace();
}
//如果有多个OutputStream,可以加分号
try(OutputStream out1 = response.getOutputStream();
OutputStream out2 = response.getOutputStream()) {
//
} catch (IOException e) {
e.printStackTrace();
}
? 这样写还有一个好处。能获取到正确的异常,而非资源关闭时抛出的异常。 还有一点要说明的是,catch多种异常也可以合并成一个了 catch (IOException | SQLException e) {
e.printStackTrace();
}
try-with-resource的优点 1、代码变得简洁可读 ? 附Closeable 接口继承了AutoCloseable 接口,都只有一个close()方法,自己新建的类也可以实现这个接口,然后使用try-with-resource机制 public interface AutoCloseable {
void close() throws Exception;
}
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
