{"record":{"id":"68c7ff7f5f2a9083","repo":"TheAlgorithms/Java","slug":"cannot-extract-from-an-empty-heap","errorCode":null,"errorMessage":"Cannot extract from an empty heap","messagePattern":"Cannot extract from an empty heap","errorType":"exception","errorClass":"EmptyHeapException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java","lineNumber":177,"sourceCode":"                largerChildIndex = 2 * elementIndex;\n            }\n\n            swap(elementIndex, largerChildIndex);\n            elementIndex = largerChildIndex;\n\n            wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1));\n        }\n    }\n\n    /**\n     * Extracts and returns the maximum element from the heap.\n     *\n     * @return HeapElement with the highest key\n     * @throws EmptyHeapException if the heap is empty\n     */\n    private HeapElement extractMax() throws EmptyHeapException {\n        if (maxHeap.isEmpty()) {\n            throw new EmptyHeapException(\"Cannot extract from an empty heap\");\n        }\n        HeapElement result = maxHeap.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        maxHeap.add(element);\n        toggleUp(maxHeap.size());\n    }\n","sourceCodeStart":159,"sourceCodeEnd":195,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java#L159-L195","documentation":"Thrown by MaxHeap.extractMax() when the heap is empty. extractMax reads the root and then calls deleteElement(1); with no elements there is no maximum to return. This is a checked EmptyHeapException (declared throws), so callers must handle or propagate it.","triggerScenarios":"Calling extractMax before any insertElement; calling it more times than elements were inserted; an extraction loop with no occupancy check.","commonSituations":"Scheduler/job-queue drain with no pending jobs; heap sort on an empty input; test that forgot to seed.","solutions":["Check isEmpty() (or ensure a public equivalent) before calling extractMax.","Handle the checked EmptyHeapException explicitly rather than propagating it generically.","Bound the extraction loop by the known element count captured before draining."],"exampleFix":"// before\nHeapElement max = heap.extractMax();\n\n// after\nHeapElement max = null;\ntry {\n    max = heap.extractMax();\n} catch (EmptyHeapException ignored) {\n    // no elements to extract\n}","handlingStrategy":"try-catch","validationCode":"// If a public isEmpty() or equivalent is available:\n// if (!heap.isEmpty()) heap.extractMax();\n// Otherwise rely on the checked-exception handler below.","typeGuard":null,"tryCatchPattern":"try {\n    HeapElement max = heap.extractMax();\n} catch (EmptyHeapException e) {\n    // heap empty; nothing to extract\n}","preventionTips":["Track element count externally and stop draining at zero.","Handle EmptyHeapException where 'no work' is a normal outcome.","Capture size before a drain loop and iterate that many times."],"tags":["heap","max-heap","empty-state","checked-exception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}