Exception handling in JSP
Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages.
There are two ways of handling exceptions in JSP. They are:
- By errorPage and isErrorPage attributes of page directive
- By <error-page> element in web.xml file
Handling Exception using page directive attributes
The page directive in JSP provides two attributes to be used in exception handling. They’re:
- errorPage: Used to site which page to be displayed when exception occurred.
<%@page errorPage="url of the error page"%>
- isErrorPage: Used to mark a page as an error page where exceptions are displayed.
In order to handle exceptions using the aforementioned page directives, it is important to have a jsp page to execute the normal code, which is prone to exceptions. Also, a separate error page is to be created, which will display the exception. In case the exception occurs on the page with the exception prone code, the control will be navigated to the error page which will display the exception.
The following is an example illustrating exception handling using page directives:
Handling Exceptions Using error-page Element En web.xml File
This is another way of specifying the error page for each element, but instead of using the errorPage directive, the error page for each page can be specified in the web.xml file, using the <error-page> element. The syntax is as follows:
The following example illustrates using this technique to handle exceptions:
The output, in this case, is similar as in the previous one.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.