Null pointer dereference

Null pointer dereference

Description

Calling an instance method or accessing an instance field through a null reference throws NullPointerException.

Potential impact

An unhandled exception interrupts the request or background task. Repeated failures can affect service availability.

Remediation

Validate required inputs and define what a lookup returns when a value is absent. If a missing result is expected, handle it before using the value.

Examples

Before

The declarations of userService, User and UserNotFoundException are omitted.

java
public class UserController {
    public String getUserById(HttpServletRequest request) {
        String userId = request.getParameter("id");
        User user = userService.findUserById(userId);
        return user.toString();  // Throws NullPointerException if user is null.
    }
}

After

java
public class UserController {
    public String getUserById(HttpServletRequest request) {
        String userId = request.getParameter("id");
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new UserNotFoundException("User not found for id: " + userId);
        }
        return user.toString();
    }
}

The revised lookup throws UserNotFoundException when no user is found. Map that exception to an appropriate response and check that the successful User.toString() response contains no sensitive information.

Related CVEs

References