Search code examples
pythonloopsexceptionheapindex-error

Python Catching Exception But Printing Them


I have built a max heap and trying to extract max as long as there are elements. If there isn't I'm returning an IndexError. This the code I'm trying to execute:

while True:
    try:
        print hp.extract_max()
    except:
        break

and in the extract_max() method:

def extract_max(self):
    if self.size == 0:
        return IndexError
    item = self.items[0]
    self.items[0] = self.items[self.size - 1]
    self.heapify_down()
    del self.items[len(self.items) - 1]
    return item

However, the code is not breaking upon encountering an IndexError, rather printing it too. The while loop is not breaking.

<type 'exceptions.IndexError'>
<type 'exceptions.IndexError'>
....

it keeps printing the exception, without breaking the loop.

What's the problem?


Solution

  • You should be raising an exception, not returning it. Do raise IndexError.