Exception Handling in Java Servlets - JSP

If you look carefully at Listing , you will notice that the init() method throws a javax.servlet.ServletException, and the doGet() throws a java.io.IOException.

Why are these exceptions being thrown, and how are they handled? You never invoke these methods directly, so you have not written the exception handling code yourself; it is a part of the container.

In Web applications, the container will catch and handle three kinds of exception:

java.io.IOException, javax.servlet.ServletException, and javax.servlet.UnavailableException.

java.io.IOException

These are thrown when there is a problem with the output stream to the client.The doGet() in Listing uses a PrintWriter to output content to the client. Using the println() method, for example, throws an IOException.You can, therefore, pass this up to the Web container.

javax.servlet.ServletException

This is a general exception class that is thrown when the servlet cannot function correctly. The documentation says this about the ServletException class: “Defines a general exception a servlet can throw when it encounters difficulty.” What happens is that when an exception occurs within say the init() method of

your servlet, a ServletException is created using a constructor that takes in both a String message and also a Throwable object type.This Throwable object will be the root cause of the problem. Listing shows the output in the browser when a servlet fails because of a null pointer exception in the init() method.This would be displayed in the form of an HTML page.You can see in the second section that the root cause is shown.This root cause is from the Throwable object that was passed to the following ServletException constructor:

public ServletException (String message, Throwable rootCause)

Listing 1.13 The Output from a Servlet Throwing a ServletException from the init() Method

javax.servlet.UnavailableException

The javax.servlet.UnavailableException is thrown when the servlet is unavailable.This is often because of a configuration problem.You might encounter these UnavailableExceptions when you have made mistakes within the web.xml file. That is enough about servlets for now. You will be returning to them throughout the rest of the book because they are so intrinsic to Web applications.We’ll now turn our attention to the core subject of this book, the JavaServer Page.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JSP Topics