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

后端 未结 6 922
梦毁少年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 21:12

    Finally is always executed, no matter what your case is i.e

    • try-catch-finally block
    • throws

    For unchecked exceptions, java does not mandate, error handling. this being the reason, if an unchecked exception occurs in finally block then and no handling is done for that, then code written below this point (where the error has occurred) will not be executed.

    So I suggest to always handle all the exceptions may it be checked or unchecked. This way you can make sure that code block in finally is also executed no matter if unchecked exception also occurs. you have a place in sub-nest catch and Finally block to get your necessary work done.

提交回复
热议问题