Search code examples
pythonexcept

Inner Try Except in Python - How does the flow work?


We have inner try excepts like

try:

    try: (problem here)

    except: (goes here)

except: (will it go here) ??

Is that the currect flow of try excepts ? If an exception is caught inside for the outside try block , its an error or non - error ?


Solution

  • No, it will not go in the second except, unless the first one raises an exception, too.

    When you go in the except clause, you are pretty much saying "the exception is caught, I'll handle it", unless you re-raise the exception. For example, this construct can often be quite useful:

    try:
        some_code()
        try:
            some_more_code()
        except Exception as exc:
            fix_some_stuff()
            raise exc
    except Exception as exc:
        fix_more_stuff()
    

    This allows you to have many layers of "fixing" for the same exception.