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 :
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