Java Servlet Exceptions.

What about Servlets and Exceptions?

  • Exception can be handle in different ways .

Exception in the code

  • Some exceptions can be handled by adding try-catch blocks into the code.
    ...
    String num = req.getParameter("number");
    try {
      Integer i = new Integer(num);
      writer.println("You entered the number " + i.intValue());
    } catch (java.lang.NumberFormatException e) {
      writer.println(" Number is not convertable: " + num);
    }
    ...

Specify Exception in the Deployment Descriptor (web.xml)

  • Example - specify an error page for a Java exception.
    ...
    <error-page>
      <exception-type>java.lang.NumberFormatException</exception-type>
      <location>/WEB-INF/BadNumber.html</location>
    </error-page>
    ...
  • For any java.lang.NumberFormatException a new page will be returned to the client (browser).
  • Example - specify an error page for an HTTP protocal error.
    ...
    <error-page>
      <error-code>404</error-code>
      <location>/WEB-INF/NoSuchPage.html</location>
    </error-page>
    ...

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.