{"record":{"id":"e958c4cb2b1298bd","repo":"TheAlgorithms/Java","slug":"cannot-delete-from-empty-heap","errorCode":null,"errorMessage":"Cannot delete from empty heap","messagePattern":"Cannot delete from empty heap","errorType":"exception","errorClass":"EmptyHeapException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java","lineNumber":225,"sourceCode":"    /**\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\n    /**\n     * {@inheritDoc}\n     */\n    @Override\n    public void deleteElement(int elementIndex) throws EmptyHeapException {\n        if (minHeap.isEmpty()) {\n            throw new EmptyHeapException(\"Cannot delete from empty heap\");\n        }\n        if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {\n            throw new IndexOutOfBoundsException(\"Index \" + elementIndex + \" is out of heap range [1, \" + minHeap.size() + \"]\");\n        }\n\n        // Replace with last element and remove last position\n        minHeap.set(elementIndex - 1, minHeap.getLast());\n        minHeap.removeLast();\n\n        // No need to toggle if we just removed the last element\n        if (!minHeap.isEmpty() && elementIndex <= minHeap.size()) {\n            // Determine whether to toggle up or down\n            if (elementIndex > 1 && getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {\n                toggleUp(elementIndex);\n            } else {\n                toggleDown(elementIndex);\n            }\n        }","sourceCodeStart":207,"sourceCodeEnd":243,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java#L207-L243","documentation":"Thrown by MinHeap.deleteElement(int) when minHeap.isEmpty() is true at call time. Before validating the index, the method checks emptiness because accessing the last element would otherwise fail. This is the empty-state sibling of the extractMin guard.","triggerScenarios":"Calling deleteElement on a heap that was never populated. Calling deleteElement after all elements have been extracted/deleted. Deleting in a loop without an emptiness guard.","commonSituations":"Cleanup code that tries to remove a specific element from an already-drained heap. Logic that assumes a previous insert succeeded when it did not. Reusing heap instances across operations.","solutions":["Check isEmpty() before deleteElement.","Catch EmptyHeapException (it is checked) and handle the empty case gracefully.","Track heap state externally and skip deletion when the count is zero.","Re-examine the lifecycle: ensure inserts happen before any delete."],"exampleFix":"// before\nheap.deleteElement(idx); // may throw on empty heap\n\n// after\nif (!heap.isEmpty()) {\n    heap.deleteElement(idx);\n}","handlingStrategy":"try-catch","validationCode":"if (!heap.isEmpty()) {\n    heap.deleteElement(idx);\n}","typeGuard":null,"tryCatchPattern":"try {\n    heap.deleteElement(idx);\n} catch (EmptyHeapException e) {\n    // nothing to delete — safe no-op\n}","preventionTips":["Guard deleteElement with isEmpty() or catch EmptyHeapException.","Do not assume a previous insert succeeded before deleting.","Reset state assumptions when reusing heap instances."],"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"}