0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This seems to be the right way, solving my problem. I would test it more. Thanks.
0

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.

1 Comment

These blocks are dependent. After successfull execution of first block i want to run second block. If first block fails I want to return without executing second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.