TheAlgorithms/Java · error · Error
Please call solve() before fetching the solution.
Error message
Please call solve() before fetching the solution.
What it means
Thrown by `TwoSat.getSolutions` when `solve()` has not been called. The assignment array is only computed during `solve()`, so reading it earlier would return a default all-false array. Like the sibling check, this is an `Error` indicating API misuse.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/graphs/TwoSat.java:214
* @throws Error if called before {@link #solve()}
*/
boolean isSolutionExists() {
if (!isSolved) {
throw new Error("Please call solve() before checking for a solution.");
}
return hasSolution;
}
/**
* Returns one valid assignment of variables that satisfies the boolean formula.
*
* @return a boolean array where {@code result[i]} represents the truth value of
* variable {@code xᵢ}
* @throws Error if called before {@link #solve()} or if no solution exists
*/
boolean[] getSolutions() {
if (!isSolved) {
throw new Error("Please call solve() before fetching the solution.");
}
if (!hasSolution) {
throw new Error("No satisfying assignment exists for the given expression.");
}
return variableAssignments.clone();
}
/** Performs DFS to compute topological order. */
private void dfsForTopologicalOrder(int u, boolean[] visited, Stack<Integer> topologicalOrder) {
visited[u] = true;
for (int v : graph[u]) {
if (!visited[v]) {
dfsForTopologicalOrder(v, visited, topologicalOrder);
}
}
topologicalOrder.push(u);
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Call `solve()` before `getSolutions()`
- Gate `getSolutions()` behind an `isSolutionExists()` check that itself requires solve()
- Encapsulate the full sequence in a single facade method
Example fix
// before boolean[] s = ts.getSolutions(); // throws Error // after ts.solve(); boolean[] s = ts.getSolutions();
Defensive patterns
Strategy: validation
Validate before calling
ts.solve(); // must run before getSolutions()
Try / catch
try {
ts.getSolutions();
} catch (Error e) {
// solve() not called first
} Prevention
- Always call solve() before any getter
- Catch Error (not just Exception) if you defend at the call site
When it happens
Trigger: Calling `getSolutions()` without a prior `solve()`, or when `solve()` sits behind a branch that did not execute.
Common situations: Forgetting to call solve(); refactoring that drops the call; assuming construction implies solving.
Related errors
- Please call solve() before checking for a solution.
- Number of variables cannot be negative.
- Variable number must be between 1 and {numberOfVariables}
- No satisfying assignment exists for the given expression.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/dc6f9e2a456572b6.
Report an issue: GitHub.