Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When will the finally block will execute in exceptions?

 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Whether finally block is to be executed before the try ends. When will the finally block execute?

Thank you in advance
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Un-comment parts of code and try to understand... Let me know if i am wrong somewhere

 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I think what i told may be wrong ie finally block is to be executed before try ends. I read from some books that finally block executes when try ends.
Hi, John jai Thank you for replying. I don't understand clearly what you told.

// 1. Finally executes when an Exception occurs
// int a = 3/0;

// 2. Finally executes when an Error occurs
// String name = "Moose";
// if(name.equals("Moose")){
// throw new Error();

Finally will execute if there is no exception also. I think only after try and catch executes, finally will execute.


If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Let me know if i am wrong
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just wanted to show in the code that finally gets executed even an Exception or an Error occurs in the try block. And you are right in the below statement.
If the JVM exits while the try or catch code is being executed, then the finally block may not execute.

Could you please share a simple code to demonstrate this statement?
Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic