Handling exceptions thrown by other servlets is crucial for building robust, user-friendly web applications.
There are multiple ways to handle exceptions in a Java servlet-based application, and it all depends on how centralized and graceful you want the handling to be.
✅ 1. Handle Exceptions with web.xml
– Centralized Error Pages
The classic and cleanest way is to configure exception handling in web.xml
.
📄 Example:
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/notfound.jsp</location>
</error-page>
🔧 What This Does:
- If any servlet in your app throws a
NullPointerException
, the container forwards the user to/error.jsp
. - If a 404 error (resource not found) occurs, user is redirected to
/notfound.jsp
.
You can use these placeholders in JSP pages:
<%= exception %> <!-- To show the actual exception -->
✅ 2. Handle Exceptions in the Servlet Itself
You can always use try-catch
in individual servlets:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
try {
// risky code
} catch (Exception e) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
res.getWriter().write("Oops! Something went wrong.");
}
}
✔️ Good for specific or critical operations
✖️ But clutters the servlet and doesn’t centralize error handling
✅ 3. Use a Filter for Global Exception Handling
If you want to catch exceptions from any servlet globally, create a Filter:
@WebFilter("/*")
public class ExceptionHandlerFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (Throwable e) {
HttpServletResponse res = (HttpServletResponse) response;
res.setStatus(500);
res.getWriter().write("Global Error Handler: " + e.getMessage());
}
}
}
✔️ Great for catching unexpected exceptions across the whole app
✔️ Centralized error logging
✖️ Not ideal for handling specific exception types differently
✅ 4. Custom Error Servlet
You can map exceptions to a dedicated servlet instead of a JSP:
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/ErrorHandler</location>
</error-page>
🧠 In your ErrorHandler
servlet:
public class ErrorHandler extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
res.getWriter().write("Exception: " + throwable);
}
}
🧠 Summary Table
Method | Scope | Use When… |
---|---|---|
web.xml <error-page> | Application-wide | You want clean and declarative error pages |
try-catch in servlet | Servlet-specific | You want tight control over a risky block |
Global Filter with try-catch | Entire app | You want global error logging or fallback |
Error handling servlet | App-wide, customizable | You want structured error recovery |