Skip to content

Python nested try-except

  • by

If you do Python nested try-except, then each of this try-catch will handle different exceptions. Earlier we have seen exceptions at the same level. But, the objective of python nested try-catch is to find errors at different levels of code.

Python nested try-except example

Simple example code.

from math import sqrt, log

from numpy import arcsin

x = 5
message = None
try:
try:
x1 = sqrt(x)
except Exception:
message = "can't take sqrt"
raise
try:
x1 = log(x1 - 4)
except Exception:
message = "can't compute log"
raise
try:
x2 = arcsin(x1)
except Exception:
message = "Can't calculate arcsin"
raise
except Exception:
print(message)

Output:

Python nested try-except example

How to use nested try/catch in python?

Answer: Use the try block with the inner try-except clause (which is required).

try:
    # do something risky

    try:
        # do another risky thing
    except:  # <-- this is required
        # handle the inner exception

except Exception as exc:
    # handle outer exception

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading