JSP exception

Like Java, exceptions can also be occurred in JSP. To handle these exceptions, JSP exception object is used.

Handling exceptions in JSP using exception object is much easier approach. This object is needed to be declared in a separate exception page. The exception page path is provided to the current page within page directive.

However, try catch block can also be used to handle these exceptions. 

Example of exception

In this example, we use exception object to handle the exceptions. The result is generated on the basis of division of the provided numbers. If inappropriate number is given in the input then an exception occurs. 

index.jsp

<form action="fetch.jsp">
Number1:<input type="text" name="num1"> <br>
Number2:<input type="value" name="num2"> <br>
<input type="submit" value="go">
</form>

fetch.jsp

<%@ page errorPage="Errorgen.jsp"%>
<%
String s1=request.getParameter("num1");
String s2=request.getParameter("num2");
int i1=Integer.parseInt(s1);
int i2=Integer.parseInt(s2);
int sum=i1/i2;
out.println("Result:"+sum);
%>
Errorgen.jsp
<%@ page isErrorPage="true"%>
<html>
<body>
Exception Occurs: <%=exception%>
</body>
</html>
Output: