Skip to content

Nested try-except Python

  • by

You can do a Nested try-except in Python. The try...except statement is used in Python to catch exceptions. You can take try-except-finally blocks inside try block. You can take try-except-finally blocks inside except block. You can take try-except-finally blocks inside finally block

Nested try-except Python

Simple example code.

try:
   print("outer try block")
   try:
       print("Inner try block")
   except ZeroDivisionError:
       print("Inner except block")
   finally:
       print("Inner finally block")
except:
   print("outer except block")
finally:
   print("outer finally block")

Output:

Nested try-except Python

OR

try:
    print("outer try block")
    print(10 / 0)
    try:
        print("Inner try block")
    except ZeroDivisionError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")

OR

try:
    print("outer try block")
    try:
        print("Inner try block")
        print(10 / 0)
    except ZeroDivisionError:
        print("Inner except block")
    finally:
        print("Inner finally block")
except:
    print("outer except block")
finally:
    print("outer finally block")

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *