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.
<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>
division.jsp page, we have specified
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” %>).
<%@ 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.
<%@ page isErrorPage="true" %> Got this Exception: <%= exception %> Please correct the input data.
Screen with two input fields for user to enter two integer numbers.
Arithmetic Exception message when user provided the second number as zero.