如何通过 try / except 正确处理 KeyError 异常?

How to handle KeyError exceptions properly via try / except?

为澄清而编辑:我正在尝试做一个学校练习,要求我构建接收元素和元组的函数,如果元素在元组中,它 returns 它的位置在反向即:

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

打印

[3, 0]

但是如果元组中不存在该元素,则应发送 KeyError 说 "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

它仍然没有按预期工作,因为如果我给它元素 1 和元组 (2,3) 它 returns 一个空列表而不是键错误,当我问的时候,reverse() 在第二个 if 上不工作,不知道为什么。

P.S。如果您想对我可以改进代码的方式发表评论,那就太棒了,对于断言部分也是如此!

我认为您的问题在于缩进。我认为你的目标是...

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

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

如何检查元素 index 是否在元组中。如果该元素不存在,则 return element not in tuple 异常 ValueError 如下所示:

def in_tuple(elem, tuplo):

    try:
        return tuplo.index(elem)
    except ValueError:
        return 'element not in tuple'

print in_tuple(1, (2, 3))

我觉得你误解了你的任务。我认为您不需要使用 tryexcept 来捕获函数内部的异常,而是您应该自己引发异常(并且可能使用 try/except 在函数外处理它)。

试试类似这样的东西,看看它是否满足您的需要:

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")