{"record":{"id":"ad9a8a95384b69db","repo":"TheAlgorithms/Python","slug":"empty-heap","errorCode":null,"errorMessage":"Empty heap","messagePattern":"Empty heap","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"data_structures/heap/heap.py","lineNumber":194,"sourceCode":"        >>> h.extract_max()\n        514\n\n        >>> h = Heap()\n        >>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])\n        >>> h.extract_max()\n        9\n        \"\"\"\n        if self.heap_size >= 2:\n            me = self.h[0]\n            self.h[0] = self.h.pop(-1)\n            self.heap_size -= 1\n            self.max_heapify(0)\n            return me\n        elif self.heap_size == 1:\n            self.heap_size -= 1\n            return self.h.pop(-1)\n        else:\n            raise Exception(\"Empty heap\")\n\n    def insert(self, value: T) -> None:\n        \"\"\"\n        insert a new value into the max heap\n\n        >>> h = Heap()\n        >>> h.insert(10)\n        >>> h\n        [10]\n\n        >>> h = Heap()\n        >>> h.insert(10)\n        >>> h.insert(10)\n        >>> h\n        [10, 10]\n\n        >>> h = Heap()\n        >>> h.insert(10)","sourceCodeStart":176,"sourceCodeEnd":212,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/heap/heap.py#L176-L212","documentation":"Raised by Heap.pop() (heap/heap.py) when heap_size == 0: the if/elif chain handles sizes >= 2 and == 1, and the else raises generic Exception('Empty heap'). Popping from an empty max heap has no element to return. Note this is a bare Exception, not IndexError/ValueError, so `except IndexError` will NOT catch it — a known wart of this implementation.","triggerScenarios":"h.pop() on a fresh Heap(); popping more times than elements inserted (e.g. drain loop that pops n+1 times); popping after exceptions interrupted inserts.","commonSituations":"Drain loops like `while True: h.pop()`; top-N extraction where the requested N exceeds heap size; reusing a heap object across test cases without re-initialization.","solutions":["Guard with emptiness check before popping: `while h.heap_size > 0: h.pop()`","Catch the generic exception: `except Exception` — but prefer the guard, since the class is bare Exception (matches nothing narrower)","Pop at most len elements: iterate `for _ in range(h.heap_size)`"],"exampleFix":"# before\nwhile True:\n    top = h.pop()  # eventually Exception('Empty heap')\n\n# after\nwhile h.heap_size > 0:\n    top = h.pop()","handlingStrategy":"validation","validationCode":"while h.heap_size > 0:\n    top = h.pop()","typeGuard":null,"tryCatchPattern":"try:\n    top = h.pop()\nexcept Exception as e:  # NOTE: bare Exception — not IndexError/ValueError\n    if str(e) != 'Empty heap':\n        raise\n    top = None","preventionTips":["Always bound pop loops by h.heap_size","Never rely on `except IndexError` here — the implementation raises bare Exception","Re-initialize the Heap between test cases instead of reusing a drained one"],"tags":["heap","empty-state","pop","generic-exception"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}