Should I use finally after try/except?

Viewed 61

I have a bunch of functions similar to this structure:

def df():
    try:
        foo = #do some computation
    except Exception:
        foo = #do other computation
    return foo

I was wondering what would be the difference with this other implementation:

def df():
    try:
        foo = #do some computation
    except Exception:
        foo = #do other computation
    finally:
        return foo

What should I use in this case? I see it a little bit redundant and also I'm concerned of the time execution, because I have many more functions with this same architecture and I don't know if adding finally would increase the execution time too much or not.

2 Answers

If you are catching a generic exception like that and not throwing it back to the calling method then both are functionally the same. The finally keyword is guaranteed to run after the try/catch has processed so in those examples, it makes no real difference. Typically, the finally keyword is used to ensure thread state or connection closures after execution of the try/catch block. If those are truly representative of your code then I wouldn’t use finally.

"finally" is executed even if the exception is raised. In your specific case it wouldn't be required.

Related