Handling Exceptions

Exceptions are just a way to indicate that there is an error, where an exception handling is an error handling mechanism that is built-in into the language.

We may encounter with different types of exceptions while writing the JSP code.

  • Checked exceptions,
  • Unchecked exceptions,
  • Error.

Checked exceptions is an exception that is typically a user error or a problem that cannot be fore seen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Runtime exceptions : A runtime exception is an exception that occurs that probably would have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will raise. They are also ignored at the time of compilation.

These exceptions may occur anytime in our web application, so handling exception is a safer side for the web developer because it is quite obvious that we don’t want to show an error stack trace to any random user surfing our web application.

Exception handling in JSP can be achieved using three ways :

  • using simple try-catch block,
  • using isErrorPage and ErrorPage attribute of page directive,
  • using <error-page> tag in deployment descriptor.

Using try-catch block :

jsp23

When we develop a JSP application, it is advisable not to use the traditional error handling within the JSP page inside a scriptlet.

Instead, it is advisable to use the isErrorPage and ErrorPage attributes of the @page directive.

jsp24

Using <error-page> tag in deployment descriptor file :

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/error.jsp</location>
</error-page>

<error-page>
 <exception-type>java.lang.ArithmeticException</exception-type>
 <location>/error.jsp</location>
</error-page>

<error-page>
  <error-code>404</error-code>
  <location>/error.jsp</location>
</error-page>