一个块中有多个try代码

时间:2021-12-11 15:16:12

I have a problem with my code in the try block. To make it easy this is my code:

我在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

Is something like this possible?

这样的事情可能吗?

4 个解决方案

#1


40  

You'll have to make this separate try blocks:

你必须制作这个单独的try块:

try:
    code a
except ExplicitException:
    pass

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

This assumes you want to run code c only if code b failed.

这假设您只想在代码b失败时运行代码c。

If you need to run code c regardless, you need to put the try blocks one after the other:

如果你需要运行代码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

I'm using except ExplicitException here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError, KeyboardInterrupt and SystemExit as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.

我在这里使用除了ExplicitException,因为盲目地忽略所有异常绝不是一个好习惯。你将忽略MemoryError,KeyboardInterrupt和SystemExit,否则你通常不想忽略或拦截,如果没有某种重新提升或有意识的处理原因。

#2


3  

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

提取(重构)您的陈述。并使用和和的魔力决定何时短路。

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

#3


2  

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

你可以使用fuckit模块。使用@fuckit装饰器将代码包装在一个函数中:

@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

#4


1  

If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.

如果你不想链接(大量的)try-except子句,你可以循环尝试你的代码并在第一次成功时中断。

Example with codes which can be put into functions:

可以放入函数的代码示例:

for code in (
    lambda: a / b,
    lambda: a / (b + 1),
    lambda: a / (b + 2),
    ):
    try: print(code())
    except Exception as ev: continue
    break
else:
    print("it failed: %s" % ev)

Example with arbitrary codes (statements) directly in the current scope:

直接在当前范围内使用任意代码(语句)的示例:

for i in 2, 1, 0:
    try:
        if   i == 2: print(a / b)
        elif i == 1: print(a / (b + 1))
        elif i == 0: print(a / (b + 2))
        break        
    except Exception as ev:
        if i:
            continue
        print("it failed: %s" % ev)

#1


40  

You'll have to make this separate try blocks:

你必须制作这个单独的try块:

try:
    code a
except ExplicitException:
    pass

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

This assumes you want to run code c only if code b failed.

这假设您只想在代码b失败时运行代码c。

If you need to run code c regardless, you need to put the try blocks one after the other:

如果你需要运行代码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

I'm using except ExplicitException here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError, KeyboardInterrupt and SystemExit as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.

我在这里使用除了ExplicitException,因为盲目地忽略所有异常绝不是一个好习惯。你将忽略MemoryError,KeyboardInterrupt和SystemExit,否则你通常不想忽略或拦截,如果没有某种重新提升或有意识的处理原因。

#2


3  

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

提取(重构)您的陈述。并使用和和的魔力决定何时短路。

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

#3


2  

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

你可以使用fuckit模块。使用@fuckit装饰器将代码包装在一个函数中:

@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

#4


1  

If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.

如果你不想链接(大量的)try-except子句,你可以循环尝试你的代码并在第一次成功时中断。

Example with codes which can be put into functions:

可以放入函数的代码示例:

for code in (
    lambda: a / b,
    lambda: a / (b + 1),
    lambda: a / (b + 2),
    ):
    try: print(code())
    except Exception as ev: continue
    break
else:
    print("it failed: %s" % ev)

Example with arbitrary codes (statements) directly in the current scope:

直接在当前范围内使用任意代码(语句)的示例:

for i in 2, 1, 0:
    try:
        if   i == 2: print(a / b)
        elif i == 1: print(a / (b + 1))
        elif i == 0: print(a / (b + 2))
        break        
    except Exception as ev:
        if i:
            continue
        print("it failed: %s" % ev)