How to create JSP error page to handle exceptions?

In this example you will learn how to handle exceptions in JSP page. JSP have a build-in mechanism for error handling which is a special page that can be used to handle every errors in the web application. To define a page as an error page we use the page directive and enable the isErrorPage attribute by setting the value to true.

Here is an example of a JSP error page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
    <title>Error Page</title>
</head>
<body>
<h1>An error has occurred.</h1>

<div style="color: #F00;">
    Error message: <%= exception.toString() %>
</div>
</body>
</html>

We have define the error page. The next steps is how to tell other JSP pages to use the error page to handle errors when uncaught exception occurred. To do this we again use the page directive. Set the errorPage attribute of this directive to point to the error page. For instance in the example below we set it to errorPage.jsp.

If we try to access the errorTest.jsp as shown in the snippet below. It will throw an exception because we try to convert an invalid string into a number. Because we are not handling the error in the page the error page will comes up and show the exception messages.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="/errorPage.jsp" %>
<html>
<head>
    <title>My Sample Page</title>
</head>
<body>
<h1>This page throws an error:</h1>

<%
    int number = Integer.parseInt("Hello, World!");
%>
</body>
</html>
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply