如何在python中的一个块中写多个try语句? [英] How to write multiple try statements in one block in python?

查看:2597
本文介绍了如何在python中的一个块中写多个try语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做:

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

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

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

最好的问候

推荐答案

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

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

使用 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'

这篇关于如何在python中的一个块中写多个try语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆