## Why is this an issue?

Servlets are components in Java web development, responsible for processing HTTP requests and generating responses. In this context, exceptions are used to handle and manage unexpected errors or exceptional conditions that may occur during the execution of a servlet.

Catching exceptions within the servlet allows us to convert them into meaningful, user-friendly messages. Otherwise, failing to catch exceptions will propagate them to the servlet container, where the default error-handling mechanism may impact the overall security and stability of the server.

Possible security problems are:

1. Vulnerability to denial-of-service attacks: Not caught exceptions can leave the servlet container in an unstable state, which can exhaust the available resources and make the system unavailable in the worst cases.
2. Exposure of sensitive information: Exceptions handled by the servlet container, by default, expose detailed error messages or debugging information to the user, which may contain sensitive data such as stack traces, database connection, or system configuration.

Unfortunately, servlet method signatures do not force developers to handle `IOException` and `ServletException`:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    }

To prevent this risk, this rule enforces all exceptions to be caught within the "do*" methods of servlet classes.

## How to fix it

Surround all method calls that may throw an exception with a `try/catch` block.

### Code examples

In the following example, the `getByName` method may throw an `UnknownHostException`.

#### Noncompliant code example

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
      InetAddress addr = InetAddress.getByName(request.getRemoteAddr()); // Noncompliant
      //...
    }

#### Compliant solution

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
      try {
        InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
        //...
      }
      catch (UnknownHostException ex) {  // Compliant
        //...
      }
    }

## Resources

### Articles & blog posts

- OWASP - Top 10 2017 Category A3 - Sensitive Data Exposure
- CWE - CWE-600 - Uncaught Exception in Servlet
- CERT, ERR01-J. - Do not allow exceptions to expose sensitive information