File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Exception handling" Watch "Exception handling" New topic

Exception handling

Suresh Appagundi
Ranch Hand

Joined: Sep 22, 2003
Posts: 44
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

Joined: Oct 04, 2003
Posts: 541
just wrap your whole thing up
.... 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!

Kim Jong II (North Korea's Dear Leader) said:Nuclear weapons don't kill people, people kill people.
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
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

I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
I agree. Here's the link:
subject: Exception handling
It's not a secret anymore!