如何在python中的一个块中编写多个try语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13874666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:49:04  来源:igfitidea点击:

How to write multiple try statements in one block in python?

pythonexceptionexception-handling

提问by alwbtc

I want to do:

我想要做:

try:
    do()
except:
    do2()
except:
    do3()
except:
    do4()

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.

如果 do() 失败,则执行 do2(),如果 do2() 也失败,则执行 do3() 等等。

best Regards

此致

采纳答案by Triptych

I'd write a quick wrapper function first()for this.

我会first()为此编写一个快速包装函数。

usage: value = first([f1, f2, f3, ..., fn], default='All failed')

用法value = first([f1, f2, f3, ..., fn], default='All failed')

#!/usr/bin/env


def first(flist, default=None):

    """ Try each function in `flist` until one does not throw an exception, and
    return the return value of that function. If all functions throw exceptions,
    return `default` 

    Args: 
        flist - list of functions to try
        default - value to return if all functions fail

    Returns:
        return value of first function that does not throw exception, or
        `default` if all throw exceptions.

    TODO: Also accept a list of (f, (exceptions)) tuples, where f is the
    function as above and (exceptions) is a tuple of exceptions that f should
    expect. This allows you to still re-raise unexpected exceptions.
    """

    for f in flist:
        try:
            return f()
        except:
            continue
    else:
        return default

# Testing.

def f():
    raise TypeError

def g():
    raise IndexError

def h():
    return 1


# We skip two exception-throwing functions and return value of the last.
assert first([f, g, h]) == 1

assert first([f, g, f], default='monty') == 'monty'

回答by alexvassel

You should specify the type of the exception you are trying to catch each time.

您应该指定每次尝试捕获的异常类型。

try:
    do()
except TypeError: #for example first one - TypeError
    do_2()
except KeyError: #for example second one - KeyError
    do_3()

and so on.

等等。

回答by Fredrik H??rd

If you really don't care about the exceptions, you could loop over cases until you succeed:

如果你真的不关心异常,你可以循环遍历案例直到成功:

for fn in (do, do2, do3, do4):
    try:
        fn()
        break
    except:
        continue

This at least avoids having to indent once for every case. If the different functions need different arguments you can use functools.partial to 'prime' them before the loop.

这至少避免了必须为每个案例缩进一次。如果不同的函数需要不同的参数,您可以使用 functools.partial 在循环之前“准备”它们。

回答by gaqzi

It seems like a really odd thing to want to do, but I would probably loop over the functions and break out when there were no exception raised:

这似乎是一件很奇怪的事情,但我可能会循环遍历这些函数并在没有出现异常时中断:

for func in [do, do2, do3]:
    try:
        func()
    except Exception:
        pass
    else:
        break 

回答by sparrow

Here is the simplest way I found, just embed the try under the previous except.

这是我找到的最简单的方法,只需将 try 嵌入到之前的 except 之下。

try:
    do()
except:
    try:
        do2()
    except:
        do3()

回答by Raghu nathan

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise