Saturday, May 27, 2006

Handling Servlet Exceptions (using web.xml file)

1). Handling all Exceptions

In this you have to write the try catch block in the service method which will catch all the exceptions. In the catch block we have to throw the servlet exception.

public void service( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// some code which throws exception
} catch (Exception e) {
throw new ServletException(e.getMessage());
}
}

And after this we have to modify the web.xml file and include following lines -

<error-page>
<location>/errorPage.html</location>
</error-page>

2). Handling Exceptions by HTML Error Code

We can also handle a particuler HTML error by including the error-code in web.xml.

<error-page>
<error-code>500</error-code>
<location>/errorPage.html</location>
</error-page>

3). Handling Exceptions by java Exception Type

In this you have to write the try catch block in the service method which will catch a particular exception. In the catch block we have to throw that exception.

public void service( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// some code which throws exception
} catch (NumberFormatException ne) {
throw new NumberFormatException(ne.getMessage());
}
}

And after this we have to modify the web.xml file and include following lines -

<error-page>
<exception-type>
java.lang.NumberFormatException</exception-type>
<location>/errorPage.html</location>
</error-page>

0 Comments:

Post a Comment

<< Home