Handling Error and Exception in Servlet
We can perform exception handling in a servlet to handle exceptions thrown by the servlet.
We can also create customized error pages to display exceptions and error messages and log these messages to the application server log file.
Servlet Exceptions
The Servlet API defines two exception classes that are defined in the javax.servlet package.The two exceptions classes are ServletException and UnavailableException.
The UnavailableException class is a subclass of the ServletException.
The javax.servlet.ServletException Class
The javax.servlet.ServletException class is defined in the javax.servlet package and is subclass of the java.lang,Exception class.It defines a servlet exception that a servlet throws while processing the client request.
This class contains the getRootCause () method , which returns an object of type java,lang.Throwable that represents the root cause of the exception.
The javax.servlet.UnavailableException Class
The javax.servlet.UnavailableException exception class is thrown by a servlet when the servlet is either temporarily or permanently unavailable.The methods provided by the UnavailableException class are:
1. public boolean isPermanent()
Returns a boolean value that describes whether a servlet is permanently unavailable or not. If the servlet is permanently unavailable, this method returns true.
2. public int getUnavailableSeconds ()
Returns the time, in seconds, for which the servlet will remain unavailable.
Handling Errors
Error Messages and Status Codes
A status code is the information that the application server sends to the client about the success or failure of a client request.When the application server services a client request , it returns the status code to the client browser through the response object.
The HttpServletResponse of javax.servlet.http package defines various fields that represent status codes.
You can use these fields to send status codes from your servlet.