user2488578
user2488578

Reputation: 916

Handling exception in Servlets

I have a Servlet.

public class MyServlet extends HttpServlet
{
   protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    {
       try
       {
        CallSomeMethodInBean();
       }
       catch(Exception e)
       {
       //What to do here?
       }
    }
}

And in my Bean, I have CallSomeMethodInBean() method

public String CallSomeMethodInBean() throws Exception
{
 try
  {
    //Try something
  }
  catch(Throwable e)
  {
    throw new Exception(e);
  } 
}

And in my web.xml, I have configured error page if java.lang.Exception is thrown.

<error-page>
   <exception-type>javax.lang.Exception</exception-type>
   <location>/WEB-INF/pages/errorPage.jsp</location>
 </error-page>

Since doPost() method is calling CallSomeMethodInBean() method which throws Exception, I need to surround CallSomeMethodInBean method with try catch block and need to catch the Exception.

Whatever exception was thrown in CallSomeMethodInBean in bean was handled through web.xml configuration. So, what should I handle in doPost() method? Just pring a log message?

Upvotes: 1

Views: 1560

Answers (2)

Kojotak
Kojotak

Reputation: 2070

In this case, I would reconsider your bean. Catching a Throwable means "I can handle any problems", but your exception handling code just wraps the Throwable into checked Exception. That is every other component which wants to use your bean have to wrap it try-catch code. If you cannot handle the checked exceptions from your bean, consider wrapping them into runtime exceptions and rethrow them.

Exceptions should be use only for exceptional situations. Catching Throwable and declaring "throws Exception" is considered as a bad practice. Declare only those exceptions, which can be handled meaningfully. Catch only those exceptions, which you know how to handle them.

Upvotes: 1

smajlo
smajlo

Reputation: 972

If you dont need some specific error handling (like fixing object state etc) in this case and error page shown is enough for you, just rethrow it, or catch and ignore.

Upvotes: 0

Related Questions