Handling errors in JSP

Interview Question: How do you handle errors in JSP?
Answer: ErrorPage = "ErrorPage.jsp" is used to indicate that the web container has to execute "ErrorPage.jsp" if there is any problem in executing the actual jsp page. We also need to set isErrorPage="true" for all the pages which may throw an error. By default isErrorPage="false" for all the jsp pages.
When a problem is encountered while executing the actual jsp page, the output that is generated till that point will be discarded by the container and the output generated by the error page will be sent to the browser. Below code is a simple example which shows how to use error page. For this example I have thrown a random exception.
File: ErrorPage.jsp

<html>
<head>
<title></title>
</head>

<body>
<p style="color: red;">Error Page: Error occurred because of ...</p>
</body>
</html>
</pre>
</div>

File: ErrorPageExample.jsp

<%@ page isErrorPage="true" %>
<%@ page errorPage="ErrorPage.jsp" %>

<%
throw new ArrayIndexOutOfBoundsException();
%>

Run ErrorPageExample.jsp and you get the output as shown below:

No comments:

Post a Comment