Exception Handling in JSP
An exception is an event that occurs during the
execution of a program and it disrupts the normal working of the instructions in
the program. An exception can occur if you trying to connect to a database which
doesn't exists or the database server is down, it may be thrown if you are
requesting for a file which is unavailable, then the exception will be thrown to
you.
We can handle the exceptions in jsp by specifying
errorPage in the page directive, <%@ page errorPage = "errorPage.jsp">.
If any exception will be thrown then the control to handle the exception will be
passed to that error page where we can display a information to the user about
what's the reason behind throwing the exception.
In this example we are going to handle the run- time
exception. To make a program on this we are using three pages.
A Html Form: It is used to display a form to the user
where he will enter the first and second number.
Controller class: This class is a jsp page which
recieves the values entered by the user and prints it on the user screen. If any
exceptions exception occurs then it will forward it other page which will handle
the exception.
Exceptional Handler: This jsp page is actually an error
page to which the control will be passed by the controller when the exception is
thrown.
Code of the program is given below:
<html>
<head>
<style>
body, input { font-family:Tahoma; font-size:8pt; }
</style>
</head>
<body>
<table align="center" border=1>
<form action="formHandler.jsp" method="post">
<tr><td>Enter your first Number: </td>
<td><input type="text" name="fno" /></td></tr>
<tr><td>Enter your Second Number: </td>
<td><input type="text" name="sno" /></td></tr>
<tr ><td colspan="2"><input ty
pe="submit" value="Submit" /></td></tr>
</form>
</table>
</body>
</html>
|
<%@ page errorPage="exceptionHandler.jsp" %>
<html>
<head>
<style>
body, p { font-family:Tahoma; font-size:10pt; }
</style>
</head>
<body>
<%
int fno;
int sno;
fno = Integer.parseInt(request.getParameter("fno"));
sno = Integer.parseInt(request.getParameter("sno"));
int div=fno/sno;
%>
<p>Division is : <%= div %></p>
<p><a href="form.html">Back</a>.</p>
</body>
</html>
|
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exceptional Even Occurred!</title>
<style>
body, p { font-family:Tahoma; font-size:10pt;
padding-left:30; }
pre { font-size:8pt; }
</style>
</head>
<body>
<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>
</body>
</html>
|
Output of the program:

Output of the Program:





Download this example.
|