简体   繁体   English

Python函数包装一些异常代码

[英]Python function to wrap some exceptions code

I am catching two exceptions in Python in such way: 我以这种方式在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.

if ex1 raises an exception then I want to skip ex2. 如果ex1引发异常,那么我想跳过ex2。 if ex1 does not raise an exception the I want to try ex2. 如果ex1没有引发异常,我想尝试ex2。

What is the most elegant way to code it? 最优雅的编码方式是什么?

My current approach is to wrap it in a function block as below and use return in right place: 我当前的方法是将其包装在下面的功能块中,并在正确的位置使用return:

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

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

and then I just call the function in right place myExceptions(someArgs) 然后我只在正确的地方调用函数myExceptions(someArgs)

EDIT: This will work as you described: 编辑:这将按您描述的那样工作:

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

When an exception occurs, it skips the rest of the try block and continues at the exception... it doesn't go back. 当发生异常时,它会跳过try块的其余部分,并继续执行异常...它不会返回。


You are doing something like this: 您正在执行以下操作:

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

A better way is, as Christian suggested: 正如Christian所建议的,更好的方法是:

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

Both of which output: 两者的输出:

HENRY
Not a dog person
invalid doggo :(

Note this will skip the second set of lines automatically if the first set fails, and lets you do different things based upon which exception occurred. 请注意,如果第一行失败,它将自动跳过第二行,并允许您根据发生的异常来做不同的事情。

I think you're confused. 我觉得你很困惑。 After a KeyError above, execution continues after the except blocks. 在上述KeyError之后, except块之后将继续执行。 The rest of the try: is skipped, which is what you seem to want: 其余的try:被跳过了,这似乎是您想要的:

That's why I can do: 这就是为什么我可以这样做:

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

Only one of those prints will happen. 这些印刷品中只有一张会发生。

Python allows you to use multiple exception clause in your try/except statements . Python允许您在try/except语句中使用多个exception子句 Add all of your code from the two try blocks into one, and simply use two except clause to catch both potentially errors: 将来自两个try块的所有代码添加到一个中,然后只需使用两个else子句即可捕获两个潜在的错误:

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

How about this? 这个怎么样? However, in you should usually be more specific with exceptions, see here: https://docs.python.org/3/tutorial/errors.html for example, use "except ValueError" to only except that one type of error. 但是,在通常情况下,您应该更具体地说明异常,请参见此处: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM