In this tutorial, you will learn exception implicit object in JSP. It is an instance of java.lang.Throwable
and mainly used for exception handling in JSP. JSP exception implicit object is only available for error pages, which means a JSP page should have isErrorPage set to true in order to use exception implicit object.
JSP exception implicit object Example
In this example, user is asked to enter two integer numbers. Once the user click “Get Results” button after entering the numbers, the division.jsp
page is called. This division.jsp
page performs the division operation by dividing the first number by second number. The idea here is to check for any exception if user enters any wrong data such as second number as zero.
index.html
<html> <head> <title>Enter two Integers for Division</title> </head> <body> <form action="division.jsp"> Input First Integer:<input type="text" name="firstnum" /> Input Second Integer:<input type="text" name="secondnum" /> <input type="submit" value="Get Results"/> </form> </body> </html>
Here, in division.jsp
page, we have specified exception.jsp
as errorPage
which means if any exception occurs in this JSP page, the control will be immediately transferred to the exception.jsp
JSP page.
Note: We have used errorPage attribute of Page Directive to specify the exception handling JSP page (<%@ page errorPage=”exception.jsp” %>).
division.jsp
<%@ page errorPage="exception.jsp" %> <% String num1=request.getParameter("firstnum"); String num2=request.getParameter("secondnum"); int v1= Integer.parseInt(num1); int v2= Integer.parseInt(num2); int res= v1/v2; out.print("Output is: "+ res); %>
In the following JSP page we have set isErrorPage to true which is also an attribute of Page directive, used for making a page eligible for exception handling. Since this page is defined as a exception page in division.jsp
, in case of any exception condition this page will be invoked. Here we are displaying the error message to the user using exception implicit object.
exception.jsp
<%@ page isErrorPage="true" %> Got this Exception: <%= exception %> Please correct the input data.
Output
Screen with two input fields for user to enter two integer numbers.
Arithmetic Exception message when user provided the second number as zero.
Prahald sahu says
Chaitanya Singh , Thank You sir. Mind blowing explanation, Site name is simply beginnersbook.com , if beginners will read these post carefully then they can give all answers of related 3yrs interview question.
Ranadheer kumar says
you provide very good information all about implicit objects. If it is possible please send methods and example programs about session object and page object.