Uncaught RuntimeException and finally clause: which comes first?

前提是你 提交于 2019-12-01 03:24:15

The finally block will definitely be executed before the main method exits, and the stacktrace is printed by the JVM after that.

Maybe the stacktrace gets printed to System.err, and the two streams get mixed up in your console output in unpredictable ways (since they are produced basically simultaneously).

What happens when you print "finally" to System.err as well?

The thing is, when there is an exception thrown.. The JVM 1st execute code with inside finally block and then throw the exception if catched or it will throw the exception and terminate the thread. so here when System.exit(0) is present in the finally block it terminate the thread immediately so the JVM doesnt get chance to throw the exception. so the out put is just the "finally "

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.

there are two blocks that we can use with try those are catch and finally.

catch block is executed when any RunTime exception is thrown (before finally) and finally block is executed in the end, irrespective of exception is thrown or not.

so if you want to do something on exception being thrown then you can put that in catch(Excepion e) block.

And what are you seeing is the duty of JVM to perform what ever is written in the finally block before terminating the program execution.

And when program is terminated it by default shows you the trace of the exception thrown.

Finally method always will be executed even in case of return statement in try block ,but in some cases where throwing Errors(Run time memory) in try block there is no guarantee finally block executed completely.

In your case finally block always executed and exception throws by main method from the JVM since you are not handle the exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!