Skip to content

Java – Exception Handling

Rules

  • Always catch specific exceptions — never catch (Exception e)
  • Use custom exception classes for domain errors
  • Include meaningful messages with context
  • Log exceptions before rethrowing
  • Never use exceptions for flow control

Correct Example

try {
    return userRepository.findById(userId);
} catch (SQLException e) {
    log.error("DB error querying user {}", userId, e);
    throw new DataAccessException("Failed to fetch user: " + userId, e);
}

Incorrect Example

try {
    return userRepository.findById(userId);
} catch (Exception e) {
    e.printStackTrace();
}

Custom Exceptions

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long userId) {
        super("User not found: " + userId);
    }
}