为什么不用Catch或者最后写Try?
为什么在没有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(""); out.println(""); out.println(""); out.println("Servlet tryse "); out.println(""); out.println(""); out.println("Servlet tryse at " + request.getContextPath() + "
"); out.println(""); out.println(""); } }
如上所述,这是Java 7及更高版本中的一个特性。 try with resources
允许跳过写入finally
并关闭try-block
本身使用的所有资源。 如文件中所述
实现java.lang.AutoCloseable的任何对象(包括实现java.io.Closeable的所有对象)都可以用作资源。
请参阅此代码示例
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
块抛出exception,那么来自try
块的exception就会被压制。
另一方面,如果您正在使用try-with-resources
语句并且try
块和try-with-resources
语句都抛出exception,那么在这种情况下, try-with-resources
语句的exception将被抑制。
正如@Aaron已经在上面回答的那样,我只是想解释一下你。 希望能帮助到你。
资料来源: http : //docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
这是Java 7及更高版本中的新function。 如果没有这个,你需要一个finally
块来关闭资源PrintWriter out
。 所以上面的代码相当于:
PrintWriter out = null; try { PrintWriter out = ... } finally { if(null != out) { try { out.close(); } catch(Exception e) {} // silently ignore! } }
请参阅try-with-resources语句