Why write Try-With-Resources without Catch or Finally?

后端 未结 2 491
礼貌的吻别
礼貌的吻别 2020-12-29 01:48

Why write Try without a Catch or Finally as in the following example?

protected void processRequest(HttpServletRequest request, HttpServletResponse response)         


        
2条回答
  •  时光说笑
    2020-12-29 02:07

    This is a new feature in Java 7 and beyond. Without this, you'd need a finally block which closes the resource PrintWriter out. So the code above is equivalent to:

    PrintWriter out = null;
    try {
        PrintWriter out = ...
    } finally {
        if(null != out) {
            try {
                out.close();
            } catch(Exception e) {} // silently ignore!
        }
    }
    

    See The try-with-resources Statement

提交回复
热议问题