Table of contents
1.
Introduction
2.
Exception Implicit Object
3.
Why Exception Handling is used
4.
Exception Handling in JSP
4.1.
Example of exception handling in JSP by page directive
4.2.
Example of exception handling using error-page element in web.xml
5.
Types of exceptions in JSP
6.
Using Try...Catch Block
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Exception Implicit object and exception Handling in JSP

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

An exception is an event that occurs during the execution of a program that disrupts the flow of the program's instructions. It is excluded from the general statement or does not follow the program's rules. An exception is usually an object which is thrown at runtime. 

Exception Handling is a process to handle runtime errors. There may occur exceptions at any time in our web application. So handling exceptions is always a safer side for the web developer as it prevents the web apps from crashing.

This article will discuss Exception implicit objects and exception handling in JSP. So, let's get started with the article.

Exception Implicit Object

In JSP, an exception object is an implicit object of type java.lang.Throwable class. We use this object to print the exception. But it can only be used on error pages. Let's see a simple example of JSP Exception Implicit Object:

<%@ page isErrorPage="true" %>  
<html>  
    <body>  
             Exception occured:<%= exception %>   
    </body>  
</html> 
You can also try this code with Online Java Compiler
Run Code

Why Exception Handling is used

An Exception Handling is a process to handle runtime errors. The main benefits of Exception handling in JSP are as follows:

  • Exception handling ensures that the program's flow doesn't stop when an exception occurs.
  • We can even display error messages using the exception object.

Exception Handling in JSP

In JSP, exceptions may occur when there is an error in the code. It can be caused either by the developer or some internal error from the system. Exception handling in JSP is the same as in Java, where we manage exceptions using the Try Catch blocks. But Unlike Java, we can have exceptions in JSP also when there is no error in the code. For example, in JSP, we can have internal errors which can be caused due to many reasons.

We have two ways of exception handling in JSP. They are: 

  • By errorPage and isErrorPage attributes of page directive.
  • By <error-page> element in web.xml file.

Example of exception handling in JSP by page directive

The page directives in JSP provide us with two attributes for handling exceptions. They are:-

  • errorPage:- Used to map which page will be displayed when exceptions occur.

Syntax: <%@page errorPage="url of the error page"%>

  • isErrorPage:- Used to mark if a page is an error page where exceptions can be displayed.

Syntax: <%@page isErrorPage="true"%>

This example will define and create a page for exception handling in JSP as the error.jsp page and the pages where Exceptions may occur. In this example, we will have three files:

  • index.jsp - For taking input.
  • process.jsp - For dividing two numbers.
  • error.jsp - For exception handling. 

index.jsp:-

<form action="process.jsp">  
    Enter number1:<input type="text" name="n1" /><br/><br/>  
    Enter number2:<input type="text" name="n2" /><br/><br/>  
    <input type="submit" value="divide"/>  
</form> 
You can also try this code with Online Java Compiler
Run Code

 

process.jsp:-

<%@ page errorPage="error.jsp" %>  
<%  
      
    String number1=request.getParameter("n1");  
    String number2=request.getParameter("n2");  
      
    int a=Integer.parseInt(number1);  
    int b=Integer.parseInt(number2);  
    int c=a/b;  
    out.print("division of numbers is: "+c);  
      
%> 
You can also try this code with Online Java Compiler
Run Code

 

error.jsp:-

<%@ page isErrorPage="true" %>  
      
<h3>Exception caught</h3>  
      
The Exception is : <%= exception %> 
You can also try this code with Online Java Compiler
Run Code

 

Now, let's run our program and check for Exception by entering number1 = 12 and number2 = 0. 

Output

Example of exception handling using error-page element in web.xml

This is another approach for specifying the error page for each element in JSP, but instead of using the Page directive, the error page for every page can be specified in the web.xml file, using the <error-page> element. The syntax is as follows:

<web-app>  
      <error-page>
          <exception-type> Exception type </exception-type>
          <location> Error page url </location>
      </error-page> 
</web-app>

 

We will define and create a page for exception handling in JSP for the error.jsp page and the pages where exceptions may occur. In this example, we will have four files:

  • web.xml - For specifying the error page.
  • index.jsp - For taking input.
  • process.jsp - For dividing two numbers.
  • error.jsp - For exception handling. 

 

Web.xml:-

<web-app>  
      <error-page>
          <exception-type>java.lang.Exception</exception-type>
          <location>/error.jsp</location>
      </error-page> 
</web-app> 

 

process.jsp:-

We don't need to specify the errorPage attribute in progress.jsp file, 

<%  
      
    String number1=request.getParameter("n1");  
    String number2=request.getParameter("n2");  
      
    int a=Integer.parseInt(number1);  
    int b=Integer.parseInt(number2);  
    int c=a/b;  
    out.print("division of numbers is: "+c);  
      
%> 
You can also try this code with Online Java Compiler
Run Code

 

Error.jsp:- It is the same as the above example.

Index.jsp:- It is the same as in the above example.

 

Now, let's run our program and check for exceptions by entering number1 = 12 and number2 = 0. It will produce an output the same as the above example.

Output

Types of exceptions in JSP

Exceptions in JSP are of three types:

  1. Checked Exception: This type of Exception usually occurs due to a user fault or a problem that the programmer can't foresee. This type of Exception is usually checked at compile-time. For example, IO Exception, FileNotFoundException, SQLException, etc.
  2. Runtime Exception:- This can be defined as an exception evaded by the programmer. Generally, They are left unnoticed at compilation time. For example, NullPointer Exception, ArrayIndexOutOfBoundsException, ArithmeticException, etc.
  3. Error Exception:- It arises solely because of the programmer or user. Here we might encounter errors due to stack overflows.

Using Try...Catch Block

If we want to handle errors on the same page and need/want to take some action instead of firing an error page in JSP, we can use the try...catch block. Try…Catch Block in JSP is the same as that in Java. Let’s try to use it as an example.

<%  
      
    int a=120;  
    int b=0;
            try {
                  int c = a/b;
                  out.println("division of numbers is: " + c);
            }
            catch (Exception error) {
                  out.println("The exception is : " + error.getMessage());
            }
      
%> 
You can also try this code with Online Java Compiler
Run Code

 

The following code will produce an output as follows:

Output

FAQs

  1. Which method is better for exception handling in JSP?
    Exception handling using the error-page element in web.xml is always preferred over exception handling using page directives. We do not need to specify the errorPage attribute in every JSP page using the error-page element. Specifying a single entry in the web.xml file will handle the Exception.
     
  2. What are the methods to trace errors from the Exception Object?
    We can use the methods available for the Exception object to trace the error that caused the Exception. A few important methods are listed below:
  • getMessage() - Returns a detailed message about the occurred exception.
  • getCause() - Returns the cause of the exception.
  • toString() - Returns class name concatenated with getMessage() result.
  • printStackTrace() - Prints the result of toString() method along with the stack trace to the System.err.

Key Takeaways

We must handle Exceptions and errors appropriately in a JSP web app to prevent our app from crashing due to unexpected or unforeseen errors. In this article, we learned the following things:

  • Exception Implicit Object and its methods.
  • Handling exceptions in JSP by using page directive and by using error-page element in web.xml
  • Types of exceptions in JSP
  • Using Try…Catch block to trace exceptions and perform an action.

Don't stop here. Check out the blogs Introduction to JSPJSP - Custom TagsJSP Architecture and Lifecycle and JSP Syntax and First App.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass