Jun-02-2023, 05:53 PM
(Jun-01-2023, 03:45 PM)Calab Wrote: When I get a successful connection, it will return from the function, so never do the finally block. The db shouldn't close.
No, that's incorrect. The finally block always runs, even if you return out of the try. That's the point of the finally block.
def myfunc(): try: a = 25 return a except Exception as e: print (f"Got a problem. {e}") finally: print ("Running finally. Closing DB") answer = myfunc() print(f"I got {answer} from the function")
Output:Running finally. Closing DB
I got 25 from the function
Why not just put the close in the exception block? What do you expect to happen in finally that wouldn't happen in an exception?