Exception Handling in Servlets, JSPs & Legacy Java EE

Illustration for Exception Handling in Servlets, JSPs & Legacy Java EE
By Last updated:

Exception Handling in Servlets, JSPs & Legacy Java EE

Slug: exception-handling-servlets-jsps-legacy-java-ee
Description: Learn exception handling in Servlets, JSPs, and legacy Java EE. Explore best practices, error pages, filters, logging, and robust web app design.
Tags: Java exception handling, servlet exception handling, JSP error handling, Java EE exceptions, try-catch-finally, checked vs unchecked exceptions, custom exceptions, web application errors, best practices, exception filters
Category: Java
Series: Java-Exception-Handling


Introduction

Exception handling in Servlets, JSPs, and legacy Java EE applications is critical for building robust and user-friendly enterprise systems. Unlike standalone Java apps, web applications must deal with exceptions that occur in multi-user environments, HTTP request/response lifecycles, and distributed systems. A single unhandled exception can expose stack traces to users, cause session corruption, or even crash the server.

Think of exception handling in web apps like airport emergency protocols—passengers (users) should never see the behind-the-scenes chaos; they should only get clear directions (custom error pages) while the crew (developers) deal with the technical failure safely.


Errors vs Exceptions in Java EE

Java categorizes failure conditions into:

  • Error: Irrecoverable issues (e.g., OutOfMemoryError) that web apps should not attempt to handle.
  • Exception: Recoverable problems (e.g., SQLException, ServletException) that can be caught and handled gracefully.
  • Throwable: The root superclass for both Errors and Exceptions.

In Servlets and JSPs, the focus is usually on handling checked exceptions (like IOException, ServletException) and unchecked runtime exceptions (like NullPointerException).


Exception Handling in Servlets

1. Basic try-catch in Servlets

@WebServlet("/process")
public class ProcessServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String data = request.getParameter("data");
            int value = Integer.parseInt(data); // may throw NumberFormatException
            response.getWriter().println("Value: " + value);
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid number format");
        }
    }
}

2. Declaring exceptions with throws

Servlet methods like doGet and doPost often declare throws ServletException, IOException, ensuring the container can handle uncaught exceptions.

3. Centralized error handling with web.xml

Legacy Java EE apps used web.xml mappings to handle exceptions globally:

<error-page>
    <exception-type>java.lang.NumberFormatException</exception-type>
    <location>/errorPages/numberError.jsp</location>
</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/errorPages/serverError.jsp</location>
</error-page>

Exception Handling in JSPs

JSPs support exception handling via:

1. errorPage directive

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

2. isErrorPage directive

The target error page must declare:

<%@ page isErrorPage="true" %>
<%= exception.getMessage() %>

This ensures JSPs can gracefully handle exceptions and avoid raw stack traces.


Exception Handling in Legacy Java EE

Legacy Java EE applications often rely on:

  • Servlet Filters to intercept and log exceptions.
  • Listeners (ServletRequestListener, HttpSessionListener) to monitor lifecycle exceptions.
  • EJBs where exceptions propagate differently—application exceptions (recoverable) vs system exceptions (rollback-triggering).

Try-with-Resources for JDBC in Servlets

Database code in Servlets often uses JDBC. To prevent leaks:

try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement("SELECT * FROM users")) {
    ResultSet rs = ps.executeQuery();
    // process result set
} catch (SQLException e) {
    throw new ServletException("Database error", e);
}

This ensures automatic cleanup of resources.


Logging Exceptions in Servlets & JSPs

Proper logging is essential:

private static final Logger logger = Logger.getLogger(MyServlet.class.getName());

try {
    // risky code
} catch (Exception e) {
    logger.log(Level.SEVERE, "Error occurred in servlet", e);
}

For enterprise projects, use SLF4J + Logback/Log4j for flexible logging.


Best Practices

  • Always provide user-friendly error pages.
  • Never expose stack traces in production.
  • Use Filters or global handlers for centralized exception logging.
  • Translate low-level exceptions into meaningful business exceptions.
  • Apply try-with-resources for JDBC and I/O.
  • Monitor exceptions with APM tools (New Relic, AppDynamics).

Common Mistakes to Avoid

  • Swallowing exceptions without logging.
  • Mixing presentation (JSP) and exception handling logic.
  • Over-using printStackTrace() instead of logging frameworks.
  • Relying only on try-catch without centralized error handling.

📌 What's New in Java Versions?

  • Java 7+: Multi-catch, try-with-resources simplify servlet JDBC handling.
  • Java 8: Lambdas in filters and functional-style error handling.
  • Java 9+: Stack-Walking API for advanced debugging in servers.
  • Java 14+: Helpful NullPointerException messages reduce debugging pain.
  • Java 21: Structured concurrency improves async servlet and microservice error handling.

FAQ

1. Why use web.xml error pages instead of try-catch in Servlets?

Centralized error pages reduce code duplication and standardize user experience.

2. Can I handle all exceptions in a single JSP error page?

Yes, by mapping java.lang.Exception in web.xml, though finer granularity is preferred.

3. Should I use filters for exception handling?

Yes, filters are great for logging and wrapping exceptions before forwarding to error pages.

4. How do I prevent sensitive stack traces in JSPs?

Use errorPage directive with friendly error messages instead of printing stack traces.

5. Can EJB exceptions propagate to Servlets?

Yes. Application exceptions propagate normally, while system exceptions often trigger rollbacks.

6. What’s better: printStackTrace() or logging frameworks?

Always prefer logging frameworks like SLF4J, Logback, or Log4j for better control.

7. How do I handle database exceptions in Servlets?

Wrap them in ServletException or translate them into custom business exceptions.

8. Is exception handling different in Jakarta EE vs Java EE?

Jakarta EE is the successor, but the core concepts remain the same. Only package names have changed.

9. Can I redirect users to custom error pages dynamically?

Yes, use response.sendRedirect("/customErrorPage") in your catch block or filter.

10. Do Servlets automatically rollback transactions on exceptions?

No. You must handle JDBC transactions explicitly unless using a managed EJB container.


Conclusion & Key Takeaways

Exception handling in Servlets, JSPs, and legacy Java EE is about keeping web applications secure, stable, and user-friendly.
While modern Spring Boot and Jakarta EE provide more elegant solutions, many enterprises still maintain legacy apps where robust exception handling is critical.

Key Points:

  • Use centralized error handling with web.xml or filters.
  • Avoid exposing stack traces.
  • Log exceptions with proper frameworks.
  • Translate low-level exceptions into meaningful messages.