Uncaught RuntimeException and finally clause: which comes first?

前端 未结 5 652
终归单人心
终归单人心 2021-01-11 10:28

A RuntimeException is thrown in try block without being caught, while the finally clause invokes System.exit().



        
5条回答
  •  北海茫月
    2021-01-11 11:05

    Finally block is executed always. It is guaranteed by the language. It is executed if you try block is terminated successfully or if any exception is thrown.

    There are checked and unchecked exceptions. For unchecked exceptions (Runtime and Errors) you do not have to write catch block. But all exceptions are caught by JVM that prints the stacktrace. When your finally block terminates application it does not have the chance to print the stacktrace, so you do not see it.

    Generally exiting program in finally block is bad because it will exit even if your code runs successfully. And more generally finally block is typically needed for cleanup like closing files, sockets etc and not for more complicated business logic.

提交回复
热议问题