{"record":{"id":"754e164389bbe480","repo":"TheAlgorithms/Java","slug":"cannot-extract-from-empty-heap","errorCode":null,"errorMessage":"Cannot extract from empty heap","messagePattern":"Cannot extract from empty heap","errorType":"exception","errorClass":"EmptyHeapException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java","lineNumber":200,"sourceCode":"\n            if (smallest == elementIndex) {\n                break;\n            }\n\n            swap(elementIndex, smallest);\n            elementIndex = smallest;\n        }\n    }\n\n    /**\n     * Extracts and returns the minimum element from the heap.\n     *\n     * @return HeapElement with the lowest key\n     * @throws EmptyHeapException if the heap is empty\n     */\n    private HeapElement extractMin() throws EmptyHeapException {\n        if (minHeap.isEmpty()) {\n            throw new EmptyHeapException(\"Cannot extract from empty heap\");\n        }\n        HeapElement result = minHeap.getFirst();\n        deleteElement(1);\n        return result;\n    }\n\n    /**\n     * {@inheritDoc}\n     */\n    @Override\n    public void insertElement(HeapElement element) {\n        if (element == null) {\n            throw new IllegalArgumentException(\"Cannot insert null element\");\n        }\n        minHeap.add(element);\n        toggleUp(minHeap.size());\n    }\n","sourceCodeStart":182,"sourceCodeEnd":218,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java#L182-L218","documentation":"Thrown by MinHeap.extractMin() when minHeap.isEmpty() is true at call time. extractMin reads the first element then calls deleteElement(1), so the empty guard prevents an IndexOutOfBounds on getFirst(). This is a state precondition error: the heap must contain at least one element before extraction.","triggerScenarios":"Calling extractMin on a freshly constructed heap with no inserts. Calling extractMin more times than insertElement. Draining the heap in a loop without checking isEmpty first.","commonSituations":"Processing a stream where the first batch is empty. Reusing a heap object across work units without resetting state assumptions. Misordered init logic that extracts before population.","solutions":["Guard every extractMin call with isEmpty(): `if (!heap.isEmpty()) { ... = heap.extractMin(); }`.","Track insertion count and only extract up to that count.","Propagate EmptyHeapException in your method signature and handle it at the caller.","Use a while loop conditioned on `!heap.isEmpty()` instead of a fixed iteration count."],"exampleFix":"// before\nHeapElement min = heap.extractMin();\n\n// after\nif (heap.isEmpty()) {\n    return null; // or handle empty case\n}\nHeapElement min = heap.extractMin();","handlingStrategy":"validation","validationCode":"if (!heap.isEmpty()) {\n    HeapElement min = heap.extractMin();\n}","typeGuard":null,"tryCatchPattern":"try {\n    HeapElement min = heap.extractMin();\n} catch (EmptyHeapException e) {\n    // heap was empty — handle gracefully\n}","preventionTips":["Always guard extractMin with isEmpty().","Bound extract loops by `!heap.isEmpty()` rather than a fixed count.","Track insert count and never extract beyond it."],"tags":["heap","empty-state","data-structure","precondition","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}