Search code examples
pythonpython-3.xtry-except

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?


Solution

  • 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