Error page jsp

Guide to JSP Error Page. Here we discuss an introduction to JSP Error Page with appropriate syntax and respective programming examples

JSP Error Page

Introduction to JSP Error Page

In jsp technology code base we have created separate jsp files for web page errors in the jsp code base. To create an error page first we need to set and assign the page directive attribute in the initial stage of the jsp file we set it as is Error Page value is to be true when we need to assign the values like these type of attributes in the jsp page then we have a separate format to access the jsp exceptions using some implicit objects it will be more helpful for creating the customized error messages to the web application clients.

Syntax

When we create the jsp file as an error page we can import the page value as the basic format and syntax  as below.

<%@ page errorPage="filename.jsp"%>
<%@ page isErrorPage="true"%>
<%@ taglib uri="" prefix=""%>
<html>
<body>
---some html program codes---
</body>
</html>

The above codes are the basic syntax in web application we have to set error page in two different ways one is assigned the values with the help of directives and another thing is we have to import the error page file in the jsp file.

How does JSP Error Page work?

If we want to use the jsp page as an error page we can declare more exceptions will arise when the jsp page is to be executed. When the jsp page code is executed it will automatically call and moves to the jsp web container it should be accessed and forward the controls to the page if the particular jsp application is going to throw an exception if the exception occurs it should be thrown to the including the page directive as the beginning of the jsp page.

Whenever the directive is assigned to the page the directive makes and creates an instance of the type like “javax.servlet.jsp.ErrorData” is availabled to the so that the container will retrieve the messages, interpret the data, and also possible to display the error data information about the root cause of the errors and exceptions in the particular jsp application. We can also access the error data jsp pages using EL(Expression Language) expressions is one of the ways of the error context in the application.

Using ${pageContext.errorData.statusCode} we can retrieve the page status code and also using ${pageContext.errorData.throwable} we can retrieve the errors and throws of the errors and exceptions in the web page. We can retrieve and helps to identify the cause of the exceptions in the log files using the expression like ${pageContext.errorData.throwable.cause}.The jsp web page has the option to throw the specific errors in the page for each type of jsps.

When the jsp page throws the exceptions every time the jsp containers automatically invoke the error pages is one of the main advantages. This contains sometimes types of exceptions that will be thrown to the particular instances using the exception instance based on its parent class called Throwable class is assigned and declared the types of exceptions in the jsp pages. Basically errors are most probably ignored by the codes because we can do some things occasionally or rarely in the pages.

Errors are not generally like Exceptions basically whenever the code side programmer gets trouble situations like out of control that time it throws something like error status code, messages, etc. In programmer code logic like the memory of the arrays exceeds the beyond limits that time the out of memory error occurs, a stack overflow occurs like these types of things will be out of the scopes in programmers it also ignored in the compile-time situations.

Checked exceptions and Un-checked Exceptions(Runtime Exceptions) is a general category of the exceptions if suppose file not found exceptions we know that it is basically kind of exceptions but most probably it is like the user error the particular user, unfortunately, open the file or they do some things in the file that time its throws exceptions then runtime exceptions are ignored by the coders at the compilation time.

Examples to Implement JSP Error Page

Below are examples mentioned:

Example #1

Code:

<%@ page errorPage = "first.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
int i = 1;
if (i == 1) {
throw new RuntimeException("Error occcured!!!");
}
%>
</body>
</html>
<%@ page isErrorPage = "true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h1>Error</h1>
<p>The error is occured.</p>
<p>Below are the exceptions occured and its traced: </p>
<pre><% exception.printStackTrace(response.getWriter()); %></pre>
</body>
</html>

Output:

JSP Error Page - 1

Example #2

Code:

<html>
<head>
<title>Second Example</title>
</head>
<body>
<%
try {
int x = 1;
x = x / 0;
out.println("Result is " + x);
}
catch (Exception e) {
out.println("The exception occurred: " + e.getMessage());
}
%>
</body>
</html>

Output:

JSP Error Page - 2

Example #3

Code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<title>Second Page</title>
</head>
<body>
<h1>Error Page Occurs</h1>
<div style="color: 'green';">
The given Error message is: <%= exception.toString() %>
</div>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="https://cdn.educba.com/second.jsp" %>
<html>
<head>
<title>First Page</title>
</head>
<body>
<h1>Error Page Occurs</h1>
<%
int n = Integer.parseInt("Welcome To My Domain!");
%>
</body>
</html>

Output:

JSP Error Page - 3

Explanation: In the above three examples we used different scenarios for the jsp in web applications. The first example we used the runtime exceptions in the two different jsp files but both the files error value is set and used for catch and throw the exceptions, the second example we used numbers using mathematical expressions like infinity values will have occurred and it has to be caught and displayed it in the web page the final example we use again two different files we used css styles presentation error is to occur and we get the output has stack trace in the log files.

Conclusion

In web pages we have created and customize the web applications based on the user needs and also it may vary upon the user situations or else application update failed time error occurs on the user browser page.

Recommended Articles

This is a guide to JSP Error Page. Here we discuss an introduction to JSP Error Page with appropriate syntax and respective programming examples. You can also go through our other related articles to learn more –

  1. JSP Interview Questions
  2. JSP Scripting Elements
  3. EJB in Java
  4. JSP Architecture 
Details
Written by  
Last Updated on 21 July 2019   |   Print  Email

Generally, there are three ways to handle exceptions in a JSP page:

    • Catching the exceptions directory in the JSP page.
    • Specifying a separate JSP error page using page directive. This is called page-level exception handling.
    • Configuring mapping of exception types-error pages in web.xml file (application-level exception handling).

Let’s take closer look at each approach in details with their own benefit and drawback.

 

1. Catching exceptions directly in JSP page

This is the simplest way, as we place a try-catch block directly into the JSP page, for example:

<%@ page language="java" %>
<html>
<body>
	<%
		try {
			int x = Integer.parseInt(request.getParameter("x"))	;

			%>
			<h2>You pass the number: <%=x%></h2>
			<%

		} catch (NumberFormatException ex) {
			%>
			<h2>Error: x must be a number</h2>
			<%
		}
	%>
</body>
</html>

The above code snippet tries to parse a number from a parameter which is passed from URL query string. If the parameter is not a number (indicated by the NumberFormatException is thrown), shows an error message.

Following is a more meaningful example which is a JSP page that calculates sum of two numeric parameters passed from query string:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sum calculation</title>
</head>
<body>
	<%! 
		int x;
		int y;
	%>
	<%
		try {
			x = Integer.parseInt(request.getParameter("x"))	;
		} catch (NumberFormatException ex) {
			%>
			<h2>Error: x must be a number</h2>
			<%
			return;
		}
	
		try {
			y = Integer.parseInt(request.getParameter("y"))	;
		} catch (NumberFormatException ex) {
			%>
			<h2>Error: y must be a number</h2>
			<%
			return;
		}	
		
	%>
	<h1>
		Sum of <%=x%> and <%=y%> is <%=(x + y) %>
	</h1>
	
</body>
</html>

If the two parameters are numeric, the page displays sum of them:

Test catch exception in JSP

If either a number is not numeric, an appropriate error message is displayed:

Test catch exception in JSP - error message

Benefits:

    • Quick and easy to implement, just like traditional exception handling in pure Java code.
    • Suitable for specific, recoverable errors which the application’s workflow can continue in case the exceptions occurred.

Drawbacks:

    • This approach is generally not recommended, because it’s not a good practice to put Java code directly into JSP pages which are designed to represent view layer, not containing logic code.
    • It’s inefficient if we want to handle exceptions for many JSP pages as with this approach, it requires to duplicate try-catch blocks in every single JSP page.

2. Page-level exception handling

In this way, we use JSP page directives to specify a separate error page which will be redirected in case exceptions occurred in the normal JSP page. The following diagram depicts this approach:

jsp page-level exception handling diagram

With this approach, there are two attributes of the page directive we have to specify for handling exceptions:

  • errorPage=”path/to/error/handling/page: Used in the JSP page in which exceptions might occur. This specifies an alternate JSP page which is written solely for handling exceptions such as showing exception class name, error message and exception stack trace. When the code in this page throws an exception, the server will redirect the client to the specified error handling page.
  • isErrorPage=”true”: Used to indicate a JSP page is an error handling page so that the server will pass the exception object thrown by the original JSP page. The exception object is a subclass of java.lang.Throwable class so we can access the following details:

Throwable class diagram

Let’s see an example. Consider the following JSP page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	errorPage="error_jstl.jsp"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calculate division of two numbers</title>
</head>
<body>
<%
	int x = Integer.parseInt(request.getParameter("x"));
	int y = Integer.parseInt(request.getParameter("y"));
	
	int div = x / y;
	
%>
<h2>Division of <%=x%> and <%=y%> is <%=div%></h2>
</body>
</html>

This page calculates division of two numbers passed from parameters query string. There are two possible exceptions here:

    • The passed parameters do not have numeric values (a NumberFormatException will be thrown).
    • The dividing number is zero (an ArithmeticException will be thrown).

And here is code of the error handling page (error.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
	isErrorPage="true"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
<h2>
	Error: <%=exception.getClass().getName() %><br/>
	<%=exception.getMessage() %><br/>	
</h2>
</body>
</html>

Here are some outputs when running this example:

  • If two parameters are numeric:Test JSP page-level exception handling - success
  • If either a parameter is not numeric:Test JSP page-level exception handling - exception 1
  • If the dividing number is zero:

Test JSP page-level exception handling - exception 2

Apart from accessing the exception object using JSP scriptlet, we can use JSTL to achieve the same goal in a more convenient way. For example:

Error: ${pageContext.exception}

To print the exception stack traces using JSTL:

<c:forEach var="trace" items="${pageContext.exception.stackTrace}">
	${trace}<br/>
</c:forEach>

Here is a better version of the error.jsp page using JSTL:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	isErrorPage="true"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
	<h2>
		Error: ${pageContext.exception}  <br/>
	</h2>	

	Exception stack trace:<br/>
	
	<c:forEach var="trace" items="${pageContext.exception.stackTrace}">
		${trace}<br/>
	</c:forEach>	

</body>
</html>

Output:

Test JSP page-level exception handling - stack trace

Benefits:

    • This page-level exception handling in JSP is more convenient than using try-catch blocks, as we can create separate error handling page and re-use it across JSP pages.

Drawbacks:                                    

    • This approach specifies one error handling page for all kind of exceptions, so we can’t specify error page per exception type. For example: dbError.jsp for java.sql.SQLException, ioError.jsp for java.io.IOException, etc.
    • Error handling configuration is depending on JSP pages: Whenever a new JSP page is added, we have to specify the attribute errorPageof the page directive. When file name of an error page is changed, we have to update all the referenced JSP pages as well.
       

3. Application-level exception handling

In this way, we can configure error handling page per exception type for all JSPs and servlets of the web application, by adding some entries in the web.xml file. Here is the syntax for configuring an error page for a specific exception type:

<error-page>
	<exception-type>fully_qualified_name_of_exception_class</exception-type>
	<location>path_to_error_jsp_page</location>
</error-page>

For example:

<error-page>
	<exception-type>java.sql.SQLException</exception-type>
	<location>/dbError.jsp</location>
</error-page>

That will tell the server to redirect the clients to the dbError.jsp page whenever any JSP/Servlet throws an exception of type java.sql.SQLException. The dbError.jsp page does not have to declare the attribute isErrorPage.

Using this approach we can also specify a custom error handling page for specific HTTP error code like 404, 500… The syntax is:

<error-page>
	<error-code>HTTP_error_code</error-code>
	<location>path_to_error_jsp_page</location>
</error-page>

For example:

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

That will tell the server redirects all requests causing HTTP 404 error to the custom page 404error.jsp, instead of showing the default 404 error. Following is example code of the 404error.jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>404 Error</title>
</head>
<body>
<center>
	<h2>
		Apologize, we could not find the page you were looking for:
	</h2>
	${pageContext.errorData.requestURI}
</center>	
</body>
</html>

The errorData object provides detailed information about the error such as the request URI, status code, servlet name, and the Throwable object that caused the error:

ErrorData class diagram

Here is the output when trying to access non-exist URL on the server:

Test 404 error code handling

Benefit:

    • This application-level error handling is easy to use and independent of JSP pages so this is the most preferred way for exception handling in JSP.

Drawback:

    • The only drawback for this approach is that, every changes made to the configuration requires application/server restart, because the configuration is done in the web.xml file.

 

Related Java Exception Handling Tutorials:

  • Getting Started with Exception Handling in Java
  • How to Handle Error in Web.xml for Java web applications

 

Other JSP Tutorials:

  • Summary of EL operators with examples
  • Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
  • How to list records in a database table using JSP and JSTL
  • How to create dynamic drop down list in JSP from database
  • Sending e-mail with JSP, Servlet and JavaMail

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Обработка ошибок

Последнее обновление: 17.09.2018

Файл web.xml позволяет указать, какие страницы html или jsp будут отправляться пользователю при отправке статусных кодов ошибок.
Для этого в web.xml применяется элемент <error-page>.

Внутри этого элемента с помощью элемента <error-code> указывается
статусный код ошибки, который надо обработать. А элемент <location> указывает на путь к
странице html или jsp, которая будет отправляться пользователю.

Например, добавим в проект в папку WebContent новый файл 404.html со следующим кодом:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Not Found</title>
</head>
<body>
<h2>Resource not found!</h2>
</body>
</html>

error page in Java EE

В файле web.xml определим следующее содержимое:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <error-page>
  	<error-code>404</error-code>
  	<location>/404.html</location>
  </error-page>
</web-app>

В данном случае элемент error-code указывает, что мы будем обрабатывать ошибки со статусным кодом 404 (то есть такие ошибки,
которые подразумевают отсутствие ресурса на сервере). А элемент location указывает, что в случае обращения к несуществующему ресурсу
пользователю будет отправляться страница 404.html.

errors in web.xml in Java EE

Обработка исключений

Кроме настройки обработки стандартных ошибок протокола http,типа 404 или 403, файл web.xml позволяет настроить обработку исключений,
которые могут возникнуть при обработке запроса. Для этого в web.xml применяется элемент <exception-type.

Например, добавим в проект в папку WebContent новый файл error.jsp и определим
в нем следующий код:

<%
   String message = pageContext.getException().getMessage();
   String exception = pageContext.getException().getClass().toString();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exception</title>
</head>
<body>
<h2>Exception occurred while processing the request</h2>
<p>Type: <%= exception%></p>
<p>Message: <%= message %></p>
</body>
</html>

Данная страница jsp будет отображать информацию об исключении. Через глобальный объект pageContext в страницу передается контекст.
Если при обработке запроса возникло какое-нибудь исключение, то метод pageContext.getException() возвратит это исключение в
виде объекта Exception. И далее мы можем исследовать этот объект и вызывать его методы, например, получить тип исключения и сообщение об исключении.

Симитируем с сервлете какое-нибудь исключение:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
    	
    	int x = 0;
    	int y = 8 / x;
    }
}

В данном случае мы получаем ошибку деления на нуль, которая представлена типом java.lang.ArithmeticException.

Теперь определим следующий файл web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <error-page>
  	<exception-type>java.lang.Throwable</exception-type>
  	<location>/error.jsp</location>
  </error-page>
</web-app>

Элемент exception-type указывает, что обрабатываться будут исключения типа java.lang.Throwable. Поскольку это базовый класс для всех типов исключений,
то фактически мы будем обрабатывать все исключения. Хотя можно конкретизировать тип исключения, например, указать тот же java.lang.ArithmeticException.

Элемент location определяет страницу, которая отправляется пользователю при возникновении исключении. В данном случае это
error.jsp.

В итоге при обращении к сервлету будет сгенерировано исключение, и мы увидим информацию о нем:

Exception type in web.xml in Java EE


In this chapter. we will discuss how to handle exceptions in JSP. When you are writing a JSP code, you might make coding errors which can occur at any part of the code. There may occur the following type of errors in your JSP code −

Checked exceptions

A checked exception is an exception that is typically a user error or a problem that cannot be foreseen 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 probably could have been avoided by the programmer. As opposed to the checked exceptions, runtime exceptions are ignored at the time of compliation.

Errors

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. 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 arise. They are also ignored at the time of compilation.

We will further discuss ways to handle run time exception/error occuring in your JSP code.

Using Exception Object

The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages. Following table lists out the important methods available in the Throwable class.

S.No. Methods & Description
1

public String getMessage()

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

2

public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3

public String toString()

Returns the name of the class concatenated with the result of getMessage().

4

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.

5

public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

6

public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page.

Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage = «xxx» %> directive.

<%@ page errorPage = "ShowError.jsp" %>

<html>
   <head>
      <title>Error Handling Example</title>
   </head>
   
   <body>
      <%
         // Throw an exception to invoke the error page
         int x = 1;
         
         if (x == 1) {
            throw new RuntimeException("Error condition!!!");
         }
      %>
   </body>
</html>

We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage = «true» %>. This directive causes the JSP compiler to generate the exception instance variable.

<%@ page isErrorPage = "true" %>

<html>
   <head>
      <title>Show Error Page</title>
   </head>
   
   <body>
      <h1>Opps...</h1>
      <p>Sorry, an error occurred.</p>
      <p>Here is the exception stack trace: </p>
      <pre><% exception.printStackTrace(response.getWriter()); %></pre>
   </body>
</html>

Access the main.jsp, you will receive an output somewhat like the following −

java.lang.RuntimeException: Error condition!!!
......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:

Using JSTL Tags for Error Page

You can make use of JSTL tags to write an error page ShowError.jsp. This page has almost same logic as in the above example, with better structure and more information −

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage = "true" %>

<html>
   <head>
      <title>Show Error Page</title>
   </head>
   
   <body>
      <h1>Opps...</h1>
      <table width = "100%" border = "1">
         <tr valign = "top">
            <td width = "40%"><b>Error:</b></td>
            <td>${pageContext.exception}</td>
         </tr>
            
         <tr valign = "top">
            <td><b>URI:</b></td>
            <td>${pageContext.errorData.requestURI}</td>
         </tr>
            
         <tr valign = "top">
            <td><b>Status code:</b></td>
            <td>${pageContext.errorData.statusCode}</td>
         </tr>
            
         <tr valign = "top">
            <td><b>Stack trace:</b></td>
            <td>
               <c:forEach var = "trace" 
                  items = "${pageContext.exception.stackTrace}">
                  <p>${trace}</p>
               </c:forEach>
            </td>
         </tr>
      </table>

   </body>
</html>

Access the main.jsp, the following will be generated −

Opps...

Error:

java.lang.RuntimeException: Error condition!!!

URI:

/main.jsp

Status code:

500

Stack trace:

org.apache.jsp.main_jsp._jspService(main_jsp.java:65)

org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)

javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)

javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Using Try…Catch Block

If you want to handle errors within the same page and want to take some action instead of firing an error page, you can make use of the try….catch block.

Following is a simple example which shows how to use the try…catch block. Let us put the following code in main.jsp −

<html>
   <head>
      <title>Try...Catch Example</title>
   </head>
   
   <body>
      <%
         try {
            int i = 1;
            i = i / 0;
            out.println("The answer is " + i);
         }
         catch (Exception e) {
            out.println("An exception occurred: " + e.getMessage());
         }
      %>
   </body>
</html>

Access the main.jsp, it should generate an output somewhat like the following −

An exception occurred: / by zero 

What is Exception in JSP?

Exceptions in JSP occur when there is an error in the code either by the developer or internal error from the system. Exception handling in JSP is the same as in Java where we manage exceptions using Try Catch blocks. Unlike Java, there are exceptions in JSP also when there is no error in the code.

Types of Exceptions in JSP

Exceptions in JSP are of three types:

  1. Checked Exception
  2. Runtime Exception
  3. Error Exception

Checked Exceptions

It is normally a user error or problems which are not seen by the developer are termed as checked exceptions.

Some Checked exception examples are:

  1. FileNotFoundException: This is a checked exception (where it tries to find a file when the file is not found on the disk).
  2. IO Exception: This is also checked exception if there is any exception occurred during reading or writing of a file then the IO exception is raised.
  3. SQLException: This is also a checked exception when the file is connected with SQL database, and there is issue with the connectivity of the SQL database then SQLException is raised

Runtime Exceptions

Runtime exceptions are the one which could have avoided by the programmer. They are ignored at the time of compilation.

Some Runtime exception examples are:

  1. ArrayIndexOutOfBoundsException: This is a runtime exception when array size exceeds the elements.
  2. ArithmeticException: This is also a runtime exception when there are any mathematical operations, which are not permitted under normal conditions, for example, dividing a number by 0 will give an exception.
  3. NullPointer Exception: This is also a runtime exception which is raised when a variable or an object is null when we try to access the same. This is a very common exception.

Errors:

The problem arises due to the control of the user or programmer. If stack overflows, then error can occur.

Some examples of the error are listed below:

  1. Error: This error is a subclass of throwable which indicates serious problems that an application cannot catch.
  2. Instantiation Error: This error occurs when we try to instantiate an object, and it fails to do that.
  3. Internal Error: This error occurs when there is an error occurred from JVM i.e. Java Virtual Machine.

Error Exceptions

It is an instance of the throwable class, and it is used in error pages.

Some methods of throwable class are:

  • Public String getMessage() – returns the message of the exception.
  • Public throwablegetCause() – returns cause of the exception
  • Public printStackTrace()– returns the stacktrace of the exception.

How to Handle Exception in JSP

Here is an example of how to handle exception in JSP:

Exception_example.jsp

<%@ page errorPage="guru_error.jsp" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Exception Guru JSP1</title>
</head>
<body>
<% 
 int num = 10;
   if (num == 10)
   {
      throw new RuntimeException("Error condition!!!");
   }
 %>
   </body>
</html>

Guru_error.jsp

<%@ page isErrorPage="true" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Exception Page</title>
</head>
<body>
<p>Guru Exception has occurred</p>
<% exception.printStackTrace(response.getWriter()); %>
</body>
</html>

Explanation of the code:

Exception_example.jsp

Code Line 1: Here we are setting error page to guru_error.jsp which will be used when the error will be redirected.

Code Line 15: we are taking a variable num and setting it to 10 and checking a condition if num is 10 then to throw a Runtime Exception with the message as Error Condition.

Guru_error.jsp

Code Line 1: Here we are setting isErrorPageattribute to true.

Code Line 12: The exception has been raised in exception_example.jsp using throw object and that exception will be shown here as IsErrorPage attribute is marked as true. Using the exception (this is an object which allows the exception data to be accessed by the JSP.) object we are trying to print the stacktrace of the error which was occurred in exception_example.jsp.

When you execute the above code you get the following output:

How to Handle Exception in JSP

Output:

The exception has been raised which was thrown from exception_example.jsp using throw object of runtime exception and we get the above code.

Also guru_error.jsp is called from which Guru Exception has occurred from this file.

Summary

  • Exceptions in JSP occur when there is an error in the code either by the developer or internal error from the system.
  • Exceptions in JSP are of 3 types: Checked Exceptions, Runtime Exceptions, and Error Exceptions
  • Checked exception is normally a user error or problems which are not seen by the developer are termed as checked exceptions.
  • Runtime exceptions are the one which could have avoided by the programmer. They are ignored at the time of compilation.
  • Error exception is an instance of the throwable class, and it is used in error pages.

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

There are two ways to define the Error page in Java web application written using Servlet and JSP. The first way is page wise error page which is defined on each jsp page and if there is any unhandled exception thrown from that page, the corresponding error page will be displayed. The second approach is an application-wide general or default error page which is shown if any Exception is thrown from any Servlet or JSP and there is no page-specific error page defined.

how do make error page in servlet jsp web application javaIn this java tutorial we will see both approaches to declare error page in JSP and when should we use page specific error page and when should we choose to generate a default application-wide error page in Java web application. 


This is in continuation of my earlier post on Servlet and JSP like the top 10 Servlet interview questions and the top 10 JSP interview questions. If you have’ read them yet, you can also read them to learn about essential Servlet and JSP concepts. 

Page-Specific Error page in JSP

Every JSP page has an attribute called «errorpage» on page directive, by using this attribute you can define an error page for any particular JSP. After that, if any unhandled Exception is thrown from that JSP, this error page will be invoked. In order to make any JSP page as an error page, you need to use «isErrorPage» attribute of the page directive and mark it true. 


For example, in the below JSP pages, error.jsp is an error page that can be used to display custom error messages if any unhandled exception is thrown from login.jsp (because it is defined as error page for login.jsp)

<%@ page isErrorPage="true"%>


<%@ page errorPage="error.jsp"%>

This is a preferred way of showing error messages in Java web applications if you have custom error messages based on JSP and it also supersedes any application-wide error page defined in web.xml. You can also join these Servlet and JSP courses to learn more about page directives in JSP. 

Error page in Java Web Application JSP Servlet

Application wide Error page in Java web application

There is another way to define error pages in java web applications written using servlet and JSP. This is called an application-wide error page or default/general error page because it’s applicable to the whole web application instead of any particular servlet or JSP. Its recommended practice for every Java web application to have a default error page in addition to page-specific error pages. 

This error page is defined in web.xml by using tag <error-page>. <error-page> allows you to define custom error messages based upon HTTP error code or any Java Exception. you can define a default error message for all exceptions by specifying <exception-type> as java.lang.Throwable and it would be applicable to all exceptions are thrown from any Servlet or JSP from web application. here is an example of declaring default error page in Java web application based on HTTP Error code and Java Exception type.

Default Error page based on Exception type:

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

Default Error page based on HTTP Error code:

<error-page>
    <error-code>500</error-code>
    <location>/internal-server-error.htm</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/page-not-found-error.htm</location>
</error-page>

That’s all on how to define the custom error page in Java application both page-specific and an application-wide default error page. An important point to note is that page-specific error pages take precedence over application-wide default error pages defined in web.xml.

Other Java posts you may like

Понравилась статья? Поделить с друзьями:
  • Error page cannot be displayed please contact your service provider for more details перевести
  • Error page 404 nginx
  • Error page 404 fallback
  • Error package system does not exist
  • Error package javax xml bind annotation does not exist