尝试例外例外会创建更多例外情况

时间:2019-01-23 02:23:20

标签: python python-3.x

我仍在学习python,所以让我很幽默。我正在尝试进行文本冒险,将其作为一种学习的方式,并且正在尝试实现一种方式,使玩家能够响应提示,提示要进行“交互”的事物列表(从嵌套词典中返回字符串)。我正在尝试使程序打印“ self.location [“ interper”]“”的值。

这是给我一些问题的代码。

# give the player the ability to "talk" and touch things

    # if there is nothing to interact with, say that there is nothing
    if "interobj" not in self.location and "interper" not in self.location:
        dismiss_fx.play()
        print("There's nothing of interest here.")

    # proceed if there is
    else:
        # print the things that are in the room
        confirm_fx.play()
        print("In the area, these things stand out to " + self.name + ": ")
        if "interobj" in self.location:
            print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["interobj"])
        if "interper" in self.location:
            print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["interper"])

        # prompt the user to interact with one of the things    
        interaction = input(colorama.Fore.CYAN + colorama.Style.BRIGHT + "\nWhich do you want " + self.name + " to interact with?: ")

        # determine if the thing the user interacted with is in the location
        try:
            raise KeyError(interaction)

        except KeyError as e:
            if str(e) != self.location["interobj"]:
                raise 

            elif interaction == self.location["interobj"]:
                # return whatever was noteworthy about the object
                confirm_fx.play()
                print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["intercom"])
                print("")

            checkprog(self,interaction)

        except KeyError as e:
            if str(e) != self.location["interper"]:
                raise

            elif interaction == self.location["interper"]:
                # return whatever the character had to say
                confirm_fx.play()
                print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["intersay"])
                print("")

            checkprog(self,interaction)

        except KeyError:
            # input is invalid
            invalid_fx.play()
            print(self.name + " couldn't find a '" + interaction + "'.")
            print("")

这应该做的是:

  1. 如果存在称为“ interper”或“ interobj”的键,则提示用户输入。
  2. 解释输入并确定输入是“ interper”键还是“ interobj”键的值。
  3. 如果输入是这两个键之一的值,它将分别为“ interper”和“ interobj”输出键“ intersay”或“ intercom”的值。
  4. 如果这两个值都不是,它将返回一条消息,指出输入无效。

实际上,它只是告诉我,我处理异常的方式正在创建更多的异常。

TL; DR:有人可以以一种易于理解的方式解释异常处理吗?我不了解“筹款”功能。

如果可以帮助我,请提前谢谢。

1 个答案:

答案 0 :(得分:0)

使用try:块时,正在检查该块中的代码是否引发异常(有错误)。如果有异常,解释器将立即跳转到except块并在那里执行代码。如果没有异常,则解释器仅执行try:块中的代码,然后移至except块之后的行。当您在try块中调用raise时,您正在这样做,以便即使您的代码正常工作,也会引发“异常”,因为raise函数会自动引发异常。您只想将普通代码放在try块中而不用引发,如果有异常,它将在except块中处理它。