一个b中有多个try码

2024-05-17 04:03:54 发布

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

我的代码在try块中有问题。 为了简单起见,这是我的代码:

try:
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d
except:
    pass

有可能吗?


Tags: andto代码goifcodeitpass
3条回答

提取(重构)语句。利用andor的魔力来决定何时短路。

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

您必须将这个分开try块:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    try:
        code c
    except ExplicitException:
        try:
            code d
        except ExplicitException:
            pass

这假设您只想在code b失败时运行code c

如果需要运行code c而不考虑,则需要逐个放置try块:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    pass

try:
    code c
except ExplicitException:
    pass

try:
    code d
except ExplicitException:
    pass

我在这里使用except ExplicitException,因为盲目忽略所有异常是一个好的做法。否则,您将忽略MemoryErrorKeyboardInterruptSystemExit,您通常不希望忽略或拦截这些,而无需重新启动或有意识地处理它们。

您可以使用fuckit模块。
@fuckitdecorator将代码包装在函数中:

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

相关问题 更多 >