Is the `finally` block executed if there is a` return` inside the `try` or` catch` block?

Using the try-catch-finally construct to retrieve the database record, it seems that I need to return the value inside the try block if everything is ok (since in case of an exception, the end of the function was not intended to be reached). But if I go back inside try , will finally code be reached (to close the connection, etc.)?

+6
source share
2 answers

Yes,

The result of the try/catch expression will be the last line of the try or catch , but the finally block will always execute no matter what

+6
source

Yes.

The finally point should ensure that some kind of cleanup code runs regardless of which path the code uses to exit the try block. This happens during a normal return, when an exception is thrown and caught, and when an exception is thrown that does not fall into this try block. The only thing that will prevent its execution is if the program cannot leave the try block at all; an infinite loop inside it or a process that is somehow killed, which prevents this normal processing or something in that order. Iā€™m sure even if you exit the process from inside the try block, which will be executed by the finally block before the process really dies.

+1
source

Source: https://habr.com/ru/post/899579/


All Articles