Multiple try codes in one block Multiple try codes in one block python python

Multiple try codes in one block


You'll have to make this separate try blocks:

try:    code aexcept ExplicitException:    passtry:    code bexcept 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.

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

try:    code aexcept ExplicitException:    passtry:    code bexcept ExplicitException:    passtry:    code cexcept ExplicitException:    passtry:    code dexcept 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.


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

@fuckitdef 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


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 Truedef b():    try: # b code    except: pass # or raise    else: return Truedef c():    try: # c code    except: pass # or raise    else: return Truedef d():    try: # d code    except: pass # or raise    else: return Truedef main():       try:        a() and b() or c() or d()    except:        pass