Search code examples
javajspservletsexceptionarithmeticexception

not getting how to forward 404 page when exception occured


I am trying to handle ArithmeticException in servlet, catch block is being execute but not forwarding to error page.

I am getting ArithmeticException: / by zero.
Can someone tell why it's not forwarded to general-errorpage.jsp

web.xml

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/ErrorHandler</location>
</error-page>

<error-page>
<location>/general-errorpage.jsp</location>
</error-page>

Servlet :

@WebServlet("/ErrorHandler")
public class Abc extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {

int a=1,b=0,c=0; 

Throwable throwable = (Throwable) 
request.getAttribute("javax.servlet.error.exception");
     String servletName = (String) 
request.getAttribute("javax.servlet.error.servlet_name");

try{    
    c= a/b;
}
catch(ArithmeticException e) {
        e.printStackTrace();           

            request.setAttribute("error", "Servlet " + servletName + 
                " has thrown an exception " + throwable.getClass().getName() 
 +
                " : " + throwable.getMessage() );    
              request.getRequestDispatcher("/general-
 errorpage.jsp").forward(request, response);


    }

 }

Error page is :

<%@ page isErrorPage="true" import="java.io.*" contentType="text/html" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Error Page -  </title>
</head>
<body> 


<table><tr><td>${statusCode}</td></tr></table>
</body>
</html>

Solution

  • Your mistake is here: The code you wrote in web.xml will not even compile because whenever you are using <error-page>, you must have <exception-type> or <exception-code> tag along with it.

    <error-page>
         <location>/general-errorpage.jsp</location>
    </error-page>
    

    So please make changes in your web.xml. By using this you can handle the exception of any type : (You can also keep the exception type to java.lang.Throwable)

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/general-errorpage.jsp</location>
    </error-page>
    

    I would like to add some more, If you wanted to handle the exception for the specific error code, then you can do something like this :

    <error-page>  
        <error-code>500</error-code>  
        <location>/general-errorpage.jsp</location> 
    </error-page>  
    

    Let me know if this helps you.