I am writing the servlet , in case of exception I am redirecting to my customized error page for that i have done like this.
In web.xml
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/jsp/ErrorPage.jsp</location>
</error-page>
In Servlet,
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
//Here is all code stuff
Throw new Exception();
}catch(Exception e){
e1.printStackTrace();
}
But here ErrorPage.jsp
is not displaying , where I am going wrong can anyone explain me?
The problem is that you catch the Exception and therefore no Exception will leave your
doPost()
method. You will only be redirected error page if anException
matching the<exception-type>
(either identical or a subclass of it) leaves yourdoPost()
method.You should rethrow the
Exception
bundled in aRuntimeException
for example:Unfortunately if we're talking about a general
Exception
you can't just not catch it becausedoPost()
is declared to only throw instances ofServletException
orIOException
. You are allowed not to catch those, butjava.lang.Exception
must be caught.You're catching the exception, and only printing the stacktrace inside, so the error-page doesn't take affect, remove the try-catch or re-throw and it will work. In addition, you have some syntax errors. Try something like
You have handled the
Exception
in yourdoPost()
using ,try
andcatch
blocks. so theerrorPage.jsp
will not be invoked.<error-page>
is invoked for unhandled exceptionsA nice example tutorial Exception Handling
Read for more info Best practice error handling in JSP Servlets