Does a finally block run even if you throw a new Exception?

后端 未结 6 913
梦毁少年i
梦毁少年i 2020-12-22 20:42

In this code will someVar be set even if the catch block is executed and the second Exception is thrown?

public void someFunction() throws Excep         


        
6条回答
  •  误落风尘
    2020-12-22 20:52

    Yes, the finally blocks always runs... except when:

    • The thread running the try-catch-finally block is killed or interrupted
    • You use System.exit(0);
    • The underlying VM is destroyed in some other way
    • The underlying hardware is unusable in some way

    Additionally, if a method in your finally block throws an uncaught exception, then nothing after that will be executed (i.e. the exception will be thrown as it would in any other code). A very common case where this happens is java.sql.Connection.close().

    As an aside, I am guessing that the code sample you have used is merely an example, but be careful of putting actual logic inside a finally block. The finally block is intended for resource clean-up (closing DB connections, releasing file handles etc), not for must-run logic. If it must-run do it before the try-catch block, away from something that could throw an exception, as your intention is almost certainly functionally the same.

提交回复
热议问题