File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes When will the finally block will execute in exceptions? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When will the finally block will execute in exceptions?" Watch "When will the finally block will execute in exceptions?" New topic
Author

When will the finally block will execute in exceptions?

Dhivya rajagopal
Ranch Hand

Joined: Dec 15, 2010
Posts: 42
Hello, Whether finally block is to be executed before the try ends. When will the finally block execute?

Thank you in advance
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Un-comment parts of code and try to understand... Let me know if i am wrong somewhere

Dhivya rajagopal
Ranch Hand

Joined: Dec 15, 2010
Posts: 42
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
Bartender

Joined: May 31, 2011
Posts: 1776
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When will the finally block will execute in exceptions?