Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

except

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 ?

like image 1000
Nishant Avatar asked Mar 27 '26 20:03

Nishant


2 Answers

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.

like image 59
dmg Avatar answered Mar 29 '26 10:03

dmg


It will not reach the outside except, unless you raise another exception within that one, like this:

try:
    try:
        [][1]
    except IndexError:
        raise AttributeError
except AttributeError:
    print("Success! Ish")

Unless the inner except block raises an exception fitting for the outer block, it will not count as an error.

like image 33
Stjepan Bakrac Avatar answered Mar 29 '26 09:03

Stjepan Bakrac