1

So i wanna know what is more efficient closing connection in Finally clause or having an explicit try catch statement inside a finally is a better approach.

    try: #some try logic
    except:
        print("something")
    finally:
        try:
            my_db_session.close()
        except:
            pass

or this 1

    try: #some try logic
    except:
        print(traceback.print_exc())
    finally:
        my_db_session.close()
        

1 Answer 1

1

In my opinion, this depends on whether you care about the exception raised by my_db_session.close() or not. try: except: pass ignores that exception, but it could be better to let the caller handle it.

As for efficiency, by which you probably mean speed, I'd say there's absolutely no speed penalty for one more try/except statement.

If by efficiency you mean "making sure that the connection is definitely closed", this depends on what my_db_session.close() does in case of an exception. The finally clause is always executed, so my_db_session.close() will definitely be called.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.