In this article, we are going to reveal what happens when an exception is thrown by a JSP web page and how to handle an exception within a JSP web page.
How an exception is thrown when executing a JSP file
In the upcoming example, we are going to display how an unhandled exception is thrown when executing a JSP file.
JspException.jsp
<html>
<head>
<title>Using JSP exception object</title>
</head>
<body>
<%
int a=10, b=0, c;
c=a/b; //ArithmeticException i.e. Divide by zero exception is thrown here
out.println(c);
%>
</body>
</html>
Executing the JspException.jsp gives us the following window displaying the JasperException which is thrown due to the original exception - ArithmeticException being thrown when executing this jsp file.
JspConfig.jsp
Advertisement
How to handle an exception in a JSP file
In this example, we are going to display how to handle an exception when executing a JSP file, using the try-catch block.
JspException1.jsp
<html>
<head>
<title>Using JSP exception object</title>
</head>
<body>
<%
int a=10, b=0, c;
try
{
c=a/b; //ArithmeticException i.e. Divide by zero exception is thrown here
out.println(c);
}
catch(ArithmeticException ariExp) //matching ArithmeticExcecption is declared in "catch block"
{
out.println("We have an Exception - "+ariExp); //message related to caught exception is printed
}
%>
</body>
</html>
Executing the JspException1.jsp gives us the following window displaying that we have handled the exception of type ArithmeticException which was thrown when executing this jsp file.