• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception handling

 
Suresh Appagundi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can i handle exception gracefully when using servlets.
I don't want user to see Internal server error or any kind of Null pointer exception from the stacktrace, but a very little of error message.
if any link, which gives this information, please mention the link.
thanks in advance.
 
Tim Baker
Ranch Hand
Posts: 541
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just wrap your whole thing up
try
{
.... all your servlet code....
}catch (Exception e)
{
out.println("<html><body>Sorry an error occurred</body></html>");
// also log the error for your own use!
}
 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmmm.....
According to the servlet specification, there are 2 ways of handling exceptions: Declarative and programmatically.
1- Declarative
This is the cleanest one, you specify the error/mapping in your web.xml. Have a look at the error-page element in web.xml.
As you can see in servlets, doXXX() methods throw IOException, ServletException. This means that you can only throw these or subclasses of these exceptions. If you have your own exception, you have to wrap them in ServletException, something like this:
...
catch (yourException e)
{
throw new ServletException("blah", e)
}
another way to avoid this is (wrapping them in ServletException), when you create your exception, you can extend IOException, ServletException, or RuntimeException.
1- Programmatically
you catch the exception and call sendError() or setStatus(). sendError trigges the container to generate an error page, where as setStatus() doesn't. Have a look at these 2 methods in the servlet specification.
hope it helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic