Throwing custom exception in servlet


Suppose we want to throw ‘InvalidParamException’ from within our controller when user doesn’t specify a parameter e.g. ‘page_id’

public class PageController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException{


                if(!request.getParameterMap().containsKey("page_id")){
                     throw new InvalidParameter(new String[]{"Page id is not specified"});

                int page_id = Integer.parseInt(request.getParameter("page_id"));
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	}
	

}

but the problem is, we can’t simply throw an exception from inside the doGet method (except for RuntimeException, we can throw RuntimeException without including it in the exceptions list). Either we need to handle it by sorrounding with try/catch or we need to add ‘InvalidParamException’ in the exceptions list of method definition like this:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, InvalidParamException{
}

Since doGet method is primarily defined in ‘HttpServlet’, we can’t add an extra Exception in the method definition. What now?

Well, since ‘ServletException’ is already in the method definition we can create our InvalidParamException by extending ‘ServletException’. This way we don’t need to include ‘InvalidParamException’ in the list.

package net.hasnath.web.exceptions;

public class InvalidParamException extends ServletException {
	
	private static final long serialVersionUID = 1L;
	private String[] errArray;
	
	public InvalidParamException(String[] errArray) {
		this.errArray = errArray;
	}
	
	public String[] getErrors(){
		return errArray;
	}

}

When the exception is thrown we’ll show the following page:

File: invalidParam.jsp

<%@ page isErrorPage="true" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<html>
  <head>
      <title>My Title</title>
  </head>
  <body>
     <div id="error">
	<%
	   String[] errArray = ((net.hasnath.web.exceptions.InvalidParamException)exception).getErrors();
	   for(String str : errArray)
		out.println(str);
		
	%>	
     </div>
  </body>
<html>

If we want to show that page, we need to say that explicitly in web.xml

<error-page>
    <exception-type>buet.threebyzero.exception.InvalidParamException</exception-type>
    <location>/WEB-INF/invalidParam.jsp</location>
</error-page>

Comments

  • Thank you , It was useful tutorial , so much thanks for you .

    SomeoneJanuary 5, 2014
    • you’re welcome.

      Shamim HasnathFebruary 18, 2014

Leave a Reply