Nearby lessons

8 of 30

JSP - Error Pages (Exception Object)

📌 What You Will Learn
  • Configure error pages declaratively in web.xml
  • Configure error pages programmatically using page directive
  • Use the exception implicit object on error pages

Error Handling is essential for building robust JSP applications. This lesson explains how to configure error pages using the declarative and programmatic approaches, and how to use the exception implicit object.

Why Error Pages?

It is not recommended to show raw Java error information to end users. We need to convert technical exceptions into user-friendly messages. For this, we configure error pages.

There are 2 approaches to configure error pages:

  1. Declarative Approach — configure in web.xml (applies to the entire application)
  2. Programmatic Approach — use page directive attributes (applies to a single JSP)

1) Declarative Approach (web.xml)

Configure error pages in web.xml — these apply to the entire web application:

Example02
JCode Cell
1 
2<web-app>
3 <error-page>
4 <exception-type>java.lang.ArithmeticException</exception-type>
5 <location>/error.jsp</location>
6 </error-page>
7 
8 <error-page>
9 <error-code>404</error-code>
10 <location>/error404.jsp</location>
11 </error-page>
12</web-app>
13

2) Programmatic Approach (page directive)

Use the errorPage attribute to redirect to an error page on exception:

Example03
JCode Cell
1 
2<%-- demo.jsp: this page redirects to error.jsp on exception --%>
3<%@ page errorPage="error.jsp" %>
4<h1>The Result is: <%= 10/0 %></h1>
5

Error Page (isErrorPage)

The error page itself must be marked with isErrorPage="true". Only then is the exception implicit object available:

Example04
JCode Cell
1 
2<%-- error.jsp --%>
3<%@ page isErrorPage="true" %>
4<h1>Sorry, we are currently facing some problems. Please try again later.</h1>
5<h2>The problem is: <%= exception %></h2>
6

Which Approach is Recommended?

Declarative approach is recommended because:

  • You can customize error pages based on exception type and error code
  • The configuration is centralized in one place (web.xml)
  • If you visit the error page directly (without an exception), exception is null

Implicit Object Availability Rules

RuleDetails
Implicit objects are local variables of _jspService()Scriptlets and expressions land inside _jspService(), so they can use implicit objects
Declarations land outside _jspService()So they cannot use implicit objects
session can be disabled<%@ page session="false" %>
exception is only on error pages<%@ page isErrorPage="true" %>
📝 Key Takeaways
  • Error pages convert Java exceptions into user-friendly messages
  • Declarative approach (web.xml) is recommended over programmatic approach
  • The exception implicit object is only available on pages marked isErrorPage="true"

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3