Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle exceptions in a nested method chain and revert changes in intermediate method?

def method1(self):
    try:
        self.method2()
    except CustomException:
        print("Error")
def method2(self):
    self.a = 3
    self.method3()

def method3(self):
    raise CustomException

How can I cancel the assignment self.a = 3 in the intermediate method (method2), when the exception in method3 occurs, such that I obtain the cleanest code?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Handle the exception in method 2 to reset the variable and rethrow the error, so you can catch it in method 1:

def method1(self):
    try:
        self.method2()
    except CustomException:
        print("Error")

def method2(self):
    self.a = 3

    try:
        self.method3()
    except CustomException as e:
        self.a = None  # Reset self.a
        raise e

def method3(self):
    raise CustomException
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading