Python:处理链异常的正确方法

2024-09-30 00:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想寻找更好的方法来处理以下异常

def fun(i, j, k, l):
    try:
        do_something_1(i)
    except TimeoutException as f:
        try:
            do_something_2(j)
        except TimeoutExeption as e:
            try:
                do_something_3(k)
            except TimeoutExeption as e:
                try:
                    do_something_4(l)
                except TimeoutExeption as e:
                    raise Exception

基本的想法是尝试一些东西,如果它不起作用,尝试下一件事,等等,直到它得到它想要的或失败。但它必须遵循执行顺序

我怎样才能做得更好


Tags: 方法顺序defasexceptiondosomethingraise
3条回答

使用for循环:

for fct in [do_something_1, do_something_2, do_something_3]:
    try:
        fct(i)
        break
    except Exception:
        continue
else:
    raise Exception

可能使用循环

def fun(i):
    errors = []
    things_to_try = (thing1, thing2, thing3, thing4)
    for thing in things_to_try:
        try:
            thing(i)
        except Exception as e:
            errors.append(e)
        else:
            break
    else:
        raise Exception("Failed: %s" % errors)

您可以使用return语句尽早退出函数,以避免嵌套。如果发生异常时没有其他操作,请使用pass作为空语句,让下面的执行继续

def fun(i):
    try:
        do_something_1(i)
        return
    except TimeoutException as f:
        pass

    try:
        do_something_2(i)
        return
    except TimeoutExeption as e:
        pass

    try:
        do_something_3(i)
        return
    except TimeoutExeption as e:
        pass

    try:
        do_something_4(i)
        return
    except TimeoutException as e:
        raise Exception

对于最后一个步骤,return实际上并不是必需的,但您可以保留它以保持一致性,并避免以后添加更多步骤时出现错误

相关问题 更多 >

    热门问题