users@glassfish.java.net

servlet: try ... finally {out.close();} <-bad idea?

From: Witold Szczerba <pljosh.mail_at_gmail.com>
Date: Fri, 28 May 2010 16:22:46 +0200

Hi there,
Today I was researching servlets. As far as I can see, this is very
common conception (for example NetBeans uses such templates)

   response.setContentType("text/plain");
   PrintWriter out = response.getWriter();
   try {
       ...
       out.print...
       ...
   } finally {
       out.close();
   }

However, it looks like very bad idea to close PrintWriter in finally
block, it should be done like this:

   response.setContentType("text/plain");
   PrintWriter out = response.getWriter();
   ...
   out.print...
   ...
   out.close();


The problem with first approach is that when exception is thrown
inside try/finally block, server will send HTTP Status 200 (OK) status
with blank or partially generated page (response writer is closed
before exception has been propagated to servlet container).
In second approach, exception will prevent the "out.close();" to
happen and server will return HTTP Status 500 (internal server error),
not some partially generated page with OK status.

Does it sound good, or maybe this is a Glassfish bug?

Thanks,
Witold Szczerba

P.S.
GlassFish v3 (build 74.2)
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)
Ubuntu 10.04 32bit