除了块没有从错误中恢复

时间:2014-08-18 23:56:53

标签: python try-catch

在我的RPG的以下代码中,我处理用户输入,因此以可以处理错误的方式创建我的代码。当用户输入如下所示的诸如acquire(其带有两个参数)的游戏命令时,调用获取功能,其尝试使用分割输入的第二部分。如果用户只输入'acquire'并且分割字符串没有第二部分,我希望IndexError会引发并打印一些文本。同样,当我的代码尝试通过RawInput[1]字典访问Items并且无法找到它时,我希望引发KeyError并打印文本。这一切都不会发生在我身上。

当这些错误中的每一个都应该提高时,会发生我预期会发生的错误,但是try / except块确实会从中恢复。

Items = {
'Rapier': Item('Rapier', 1, [None, None], 2)}

def Acquire(self):
    try:
        if Pos[0] == self.Pos[0] and Pos[1] == self.Pos[1]:
            for i in range(1, 4):
                j = i - 1
                if self.Type == i and not Inventory[j]:
                    Inventory[j] = self
                    self.Pos = None
                    print(Name, 'picked up the', self.Name)
                elif None not in Inventory:
                    print(Name, 'cannot carry any more!')
        else:
            print('There is no', RawInput[1].title(), 'here')
    except KeyError:
        print('That doesn\'t exist!')
    except IndexError:
        print('Acquire takes two arguments')

def ParseInput():
    global RawInput
    RawInput = input('> ').lower().split(' ', 1)

    if RawInput[0] == 'acquire':
        Acquire(Items[RawInput[1].title().strip()])

有人可以向我解释如何修复我的代码或解释发生的事情吗?

1 个答案:

答案 0 :(得分:0)

您尝试捕获的错误不会发生在代码本身内部,而是在解释代码时发生。把try-except放在函数调用周围应该修复它。

if RawInput[0] == 'acquire':
    try:
        Acquire(Items[RawInput[1].title().strip()])
    except KeyError:
        print('That doesn\'t exist!')
    except IndexError:
        print('Acquire takes two arguments')