Before going to JSP exception handling, first we have to understand what is an exception and how it is different from errors.
Exception:An unwanted or unexpected event that interrupts the normal flow of execution is known as exception. Exception is a disadvantageous fact. So we have to handle exceptions in order to graceful termination of the program.
Error:It can be a issue with the code or a system related issue which are irrecoverable.
JSP provide 3 different ways to perform exception handling:
1. Using isErrorPage and errorPage attribute of page directive.
2. Using < error-page > tag in Deployment Descriptor.
3. Using simple try...catch block.
Example of isErrorPage and errorPage attribute isErrorPage attribute in page directive officially appoints a JSP page as an error page.
errorPage attribute in a page directive informs the Web Container that if an exception occurs in the current page, forward the request to the specified error page.
Whenever an exception occurs in sum.jsp page the user is redirected to the error.jsp page, where either you can display a nice message, or you can also print the exception trace into a file/database in the background, to check later what caused the error.
Declaring error page in Deployment Descriptor
You can also declare error pages in the DD for the entire Web Apllication. Using < error-page > tag in the Deployment Descriptor. You can even configure different error pages for different exception types, or HTTP error code type(503, 500 etc).
Declaring an error page for all type of exception
<error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page>
Declaring an error page for more detailed exception
<error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/error.jsp</location> </error-page>
Declaring an error page based on HTTP Status code
<error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page>
Using try...catch block is just like how it is used in Core Java.
<html> <head> <title>Try...Catch Example</title> </head> <body> <% try{ int i = 100; i = i / 0; out.println("The answer is " + i); } catch (Exception e){ out.println("An exception occurred: " + e.getMassage()); } %> </body> </html>
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc