【问题标题】:Try-Except exceptions creating more exceptionsTry-Except 异常创建更多异常
【发布时间】:2019-01-23 02:23:19
【问题描述】:

我还在学习 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: 有人能以易于理解的方式解释异常处理吗?我不明白“raise”功能。

如果您能帮助我,请提前感谢您。

【问题讨论】:

  • raise 函数引发异常。 所以你正在做的是捕获一个异常,然后立即抛出一个新异常。你应该在你的异常处理程序(except 块)中做的是处理你刚刚捕获的异常。
  • 您还应该限制异常处理程序中条件检查的数量。如果你捕捉到一个异常,你应该已经很清楚为什么会发生错误,而无需进行有可能进一步引发异常的条件检查。
  • 如果有帮助,请将异常处理视为投手和捕手。在其他语言中,这个比喻更容易看到,因为发生错误时异常是thrown,而catch 块会捕获它们。这种安排的好处是“捕捉器”可以位于上游调用堆栈中的任何位置。如果你不能在本地处理异常,你就让它沿着调用堆栈向上走,直到找到处理程序,或者程序出错退出。

标签: python python-3.x


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多