In this tutorial, we will discuss exception implicit object of JSP. It’s an instance of java.lang.Throwable and frequently used for exception handling in JSP. This object is only available for error pages, which means a JSP page should have isErrorPage to true in order to use exception implicit object. Let’s understand this with the help of below example –
Exception implicit Object Example
In this example we are taking two integer inputs from user and then we are performing division between them. We have used exception implicit object to handle any kind of exception in the below example.
<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 we have specified exception.jsp as errorPage which means if any exception occurs in this JSP page, the control will 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 below 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 two integer numbers.
Arithmetic Exception message when we have provided the second integer as zero.
Let us know if you have any questions regarding exception implicit object in JSP. This is one of the most frequently used implicit object while building an application in JSP. As an alternative, you can also handle exceptions in JSP by using try catch within JSP scriptlet.