Exception handling is a mechanism to handle runtime errors, so that normal flow of the program can be maintained.
Ways of exception handling in JSP:
- Using page directive (errorPage and isErrorPage attributes).
- Using <error-page> attribute of web.xml.
Exception handling example using errorPage and isErrorPage attributes:
welcome.jsp
<%@ page errorPage="errorPage.jsp" %> <html> <head> <title>isErrorPage and errorPage page directive example</title> </head> <body> <%= 0/0 %> </body> </html> |
errorPage.jsp
<%@ page isErrorPage="true" %> <html> <head> <title>isErrorPage and errorPage page directive example</title> </head> <body> <h3>Hello this is an isErrorPage and errorPage page directive example.</h3> <br/> <h3>Some exception occurred.</h3> Exception: <%=exception %> </body> </html> |
web.xml
<web-app> <welcome-file-list> <welcome-file>welcome.jsp</welcome-file> </welcome-file-list> </web-app> |
Output:
Exception handling example using <error-page> attribute:
welcome.jsp
<html> <head> <title>Exception handling example</title> </head> <body> <% out.print(10/0); %> </body> </html> |
errorPage.jsp
<%@ page isErrorPage="true" %> <html> <head> <title>error page</title> </head> <body> Occurred exception is: <%= exception %> </body> </html> |
web.xml
<web-app> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page> <welcome-file-list> <welcome-file>welcome.jsp</welcome-file> </welcome-file-list> </web-app> |
Output:
Download this example.
Next Topic: jsp:useBean, jsp:setProperty and jsp:getProperty action tag.
Previous Topic: jsp:param action tag with example.