Josh Zwiebel
Josh Zwiebel

Reputation: 1003

How to raise an exception and catch it after function execution complete?

I have a line in my code that has the potential to raise an exception, i would like to handle this execption and continue execution.

def foo():
    #good code
    if thingThatHappensSometimes:
        raise CustomException
    #code i want to execute
    return resultIwant

def bar():
    resultIwant = None
    try:
        #good code
        resultIwant = foo()
    except CustomException:
        #code that should run if an exception was raised
    finally:
        print(resultIwant)
        print('All done!')

My issue here is that there are situations where foo will raise an exception but there is nothing in the code logic preventing it from generating a result for resultIwant. Currently, if I handle the exception in bar I will not reach the end of execution for foo but If I handle the exception in foo the exception will already be handled and I will not reach the except block in bar. is there a way to solve this issue?

Upvotes: 0

Views: 65

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

raising an exception stops execution at this point, so you cannot both raise an exception and return a value. But you can return a (value, exception_or_none) tuple:

def foo():
    error = None    
    #good code
    if thingThatHappensSometimes:
        error = CustomException()
    #code i want to execute
    return resultIwant, error

def bar():
    #good code
    resultIwant, error = foo()
    if error: 
        #code that should run if an exception was raised
    print(resultIwant)
    print('All done!')

Upvotes: 1

Related Questions