java – 为什么不使用Catch或者最后编写Try-With-Resources?
作者:互联网
为什么在没有Catch或Finally的情况下编写Try,如下例所示?
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet tryse</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet tryse at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
解决方法:
如上所述,这是Java 7及更高版本中的一项功能.尝试使用资源允许跳过写入finally并关闭try-block本身使用的所有资源.如Docs所述
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
请参阅此代码示例
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
在此示例中,资源是BufferReader对象,因为该类实现了接口java.lang.AutoCloseable,无论try块是否成功执行,它都将被关闭,这意味着您不必显式地编写br.close().
另一个需要注意的重要事项是,如果你自己编写finally块,并且你的try和finally块抛出异常,那么try块的异常就会被压制.
另一方面,如果您使用try-with-resources语句并且try块和try-with-resources语句都抛出异常,那么在这种情况下,try-with-resources语句的异常将被抑制.
正如@Aaron已经在上面回答的那样,我只是想解释一下你.希望能帮助到你.
资料来源:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
标签:java,try-with-resources 来源: https://codeday.me/bug/20191004/1853151.html