Search code examples
javaexceptionservletserror-handlingstruts

Java EE / Struts Exception Handling


I have started developing Java EE web applications mainly on Struts and Servlets. Most of the codes have a try catch block within Servlet or Struts Action class.

Is it a must to have try catch block for every servlet or action? The only advantages I saw with this kind of code template is stacktrace are log to application specified logging framework such as log4j.

If the runtime exception floats up, it will be printed on the server (Tomcat / Glassfish / Weblogic) logs instead.

public class HelloWorldAction extends Action{

    public ActionForward execute(ActionMapping mapping,ActionForm form,
        HttpServletRequest request,HttpServletResponse response)
        throws Exception {

        try {
            // do all the processing here
        } catch (Exception e) {
            // log all exceptions
        }
    }

}


public class HelloWorldExample extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws IOException, ServletException {
     try {
        // do all the processing here
    } catch (Exception e) {
        // log all exceptions
    }
   }
}

Solution

    1. Catching Exception is almost never what you really want to do. Hopefully it's obvious that it's not mandatory to always have a try/catch block–it depends on what the underlying code is doing, and how you want to handle any exceptions it may throw.

    2. Catching Exception eliminates the ability to use Struts' declarative exception handling.

    I would recommend against using a filter to handle exceptions in Struts 1 since it already has a mechanism built in. If there are exceptions at the framework level they'll be displayed anyway, and they generally indicate a development, not runtime, issue.

    I echo Andrea's sentiments: unless you have a Very Good Reason, learning Struts 1 isn't useful. Consider instead Struts 2 or Spring MVC for "traditional" framework development, or Play, Grails, JRuby on Rails, etc. for a more modern approach.