【问题标题】:Python function to wrap some exceptions code用于包装一些异常代码的 Python 函数
【发布时间】:2017-05-02 22:27:14
【问题描述】:

我以这种方式在 Python 中捕获了两个异常:

#ex1
try: 
    #some code
except:
    #some code to e.g. print str

#ex2
try: 
    #some code
except: 
    #some code to e.g. print str or exit from the program.

如果 ex1 引发异常,那么我想跳过 ex2。 如果 ex1 没有引发异常,我想尝试 ex2。

最优雅的编码方式是什么?

我目前的做法是将它包装在一个功能块中,如下所示,并在正确的位置使用 return:

def myExceptions(someArgs):
    #ex1
    try: 
        #some code
    except:
        #some code
        return

    #ex2
    try: 
        #some code
    except: 
        #some code

然后我只是在正确的地方调用函数 myExceptions(someArgs)

【问题讨论】:

标签: python function exception


【解决方案1】:

编辑:这将按照您的描述工作:

try:
    msg = make_msg_fancy(msg)
    msg = check_for_spam(msg)
except MessageNotFancyException:
    print("couldn't make it fancy :(")
except MessageFullOfSpamException:
    print("too much spam :(")

当发生异常时,它会跳过 try 块的其余部分并在异常处继续......它不会返回。


你正在做这样的事情:

for person in [{"dog": "Henry"}, {}, {"dog": None}]:
    try:
        doggo = person['dog']  # can throw KeyError
    except KeyError:
        print("Not a dog person")
        continue  # skip the rest of the loop (since this is a for loop)

    try:
        print(doggo.upper())  # can throw AttributeError
    except AttributeError:
        print("No doggo :(")

正如克里斯蒂安建议的那样,更好的方法是:

for person in [{"dog": "Henry"}, {}, {"dog": None}]:
    try:
        doggo = person['dog']  # can throw KeyError
        print(doggo.upper())  # can throw AttributeError
    except KeyError:  # person dict does not contain a "dog"
        print("Not a dog person")
    except AttributeError:  # dog entry cannot be .upper()'d
        print("invalid doggo :(")

两者都输出:

HENRY
Not a dog person
invalid doggo :(

请注意,如果第一组失败,这将自动跳过第二组行,并让您根据发生的异常执行不同的操作。

我认为你很困惑。在上面的KeyError 之后,在except 块之后继续执行。 try: 的其余部分被跳过,这似乎是您想要的:

这就是我能做到的原因:

try:
    dct[key] += value
    print("Added.")
except KeyError:
    dct[key] = value
    print("New key.")

只会发生其中一种打印。

【讨论】:

  • 我执行以下操作:对于 [...] 中的人员:尝试:以 msg 作为输入运行函数,如果函数错误则引发用户定义的异常。接下来我再试一次:以 msg 作为输入运行另一个函数,如果函数错误则引发用户定义的异常。如果第一次尝试引发异常,则不要执行第二次尝试块。如果第一个尝试块没有引发异常,则执行第二个尝试块。听起来和你描述的相似吗?
  • @bluedog 如果您想添加更多详细信息,请更新您的问题
  • @BlueDog 如果您按照我们所说的那样实现它,它将对您有用。
【解决方案2】:

Python allows you to use multiple exception clause in your try/except statements。将两个 try 块中的所有代码添加到一个中,然后简单地使用两个 except 子句来捕获两个潜在的错误:

try: 
    #some code
except:
    #some code to e.g. print str
except: 
    #some code to e.g. print str or exit from the program.

【讨论】:

  • 我为两个单独的 try 块引发了两个单独的异常,因为两个 try 块有不同的代码。所以我不会按照你的例子为同一个 try 块提出两个不同的例外。
  • @BlueDog 你不需要分开 try 块。如果你想跳过第一个异常的所有代码,没有理由有两个块。
  • @BlueDog 但这会自行发生。当抛出异常时,控制传递给相关的异常处理程序,跳过 try 块中的剩余语句。如果 try 块中的语句没有引发异常,则继续执行。
  • @BlueDog 'ex1 try block exceptions' 是什么意思?如果 ex1 引发异常,则异常处理程序运行并且异常处理程序和抛出位置之间的语句被简单地跳过。异常处理程序实际上做什么没有区别
  • @BlueDog 哦,如果您认为处理程序将以某种方式按顺序执行,那么事实并非如此。无论单个处理程序做什么,都只会调用一个处理程序。您不只是下拉并开始执行下一个。我认为您应该尝试一些人们为自己发布的示例。在这一点上,您似乎试图向我们解释 Python 以您误解的方式工作。
【解决方案3】:

这个怎么样?但是,您通常应该更具体地例外,请参见此处:https://docs.python.org/3/tutorial/errors.html 例如,使用“except ValueError”来仅排除一种类型的错误。

try:
    # ex1 code
except:
    # handle the exception
else:
    # ex2 code, will only run if there is no exception in ex1

【讨论】:

  • 这对我来说似乎是最合理的答案。这是我最初的想法,但我不知道什么更好:这种方式编码或将所有内容包装在一个功能块中。
  • 这不等效,因为它从不处理“ex2 代码”引发的异常。
猜你喜欢
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多