Search code examples
pythonexceptionassert

How to handle KeyError exceptions properly via try / except?


Edited for clarification: I'm trying to do a school exercise that requires me to build function that receives an element and a tuple and in case the element is in the tuple, it returns its positions in reverse i.e:

findInTupleA (1 , (1,2,3,1)

prints

[3, 0]

But in case the element doesn't exist in the tuple, a KeyError should be sent saying "element not in tuple".

def findInTupleA(elem,tuplo):
    lista_indices = []
    i = 0
    while i < len(tuplo):
        try:
            if tuplo[i] == elem:
                lista_indices.append(i)
            i = i + 1
        except KeyError:
            return "element not in tuple"

    if len(lista_indices)>=1:
        return lista_indices[::-1]
    else:
        return lista_indices

Still it's not working as intended, since if I give it element 1 and tuple (2,3) it returns a empty list instead of the key error, and while I'm asking, reverse() isn't working on the second if, no idea why.

P.S. If you'd like to comment on ways I could improve the code it would be awesome, same for an assert part!


Solution

  • It sounds to me like you have misunderstood your assignment. I don't think you need to be using a try and except to catch an exception inside your function, but rather, you're supposed to be raising the exception yourself (and maybe using try/except outside the function to handle it).

    Try something more like this, and see if it does what you need:

    def findInTupleA(elem,tuplo):
        lista_indices = []    
        i = 0
        while i < len(tuplo):
            if tuplo[i] == elem:
                lista_indices.append(i)
            i = i + 1
    
        if len(lista_indices) >= 1:
            return lista_indices
        else:
            raise IndexError("element not in tuple")