ABCD
ABCD

Reputation: 820

How to use nested try except properly in python3.7?

I have situation where I wanted to run some line of code and if those lines runs successfully then run another few lines. In both cases there are possibilities of errors/exceptions. So I wanted to know which would be the best way to use try catch between two I mentioned below

def function_name1():
    try:
        *Run first few lines*
        try:
            *Run second few lines*
        except Exception as ex2:
            raise Exception("second Exception - wdjk")
    except Exception as ex1:
        raise Exception("first Exception - wejk")

def function_name2():
    try:
        *Run first few lines*
    except Exception as ex1:
        raise Exception("first Exception - wejk")
    try:
        *Run second few lines*
    except Exception as ex2:
        raise Exception("second Exception - wdjk")

In function_name1, I faced one issue that even if I get excption in second line i.e raise Exception("second Exception - wdjk"), code is returning or raising exception from raise Exception("first Exception - wejk"). So what would be the best way to handle this case?

Upvotes: 0

Views: 119

Answers (2)

Carlos
Carlos

Reputation: 51

If the code blocks are independent from one another, I don't see why you would nest them. The second option would be better. You can learn more about exceptions in this post by Real Python: https://realpython.com/python-exceptions/ There they talk about how try-except works.

Upvotes: 0

a_guest
a_guest

Reputation: 36339

The cleanest solution would be to run the second try/except in the else suite of the first:

try:
    # first stuff
except SomeException:
    # error handling
else:  # no error occurred
    try:
        # second stuff
    except OtherException:
        # more error handling

Upvotes: 1

Related Questions