aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Preventing finally Block from execution ... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Preventing finally Block from execution ... " Watch "Preventing finally Block from execution ... " New topic
Author

Preventing finally Block from execution ...

Murgan Sub
Greenhorn

Joined: Feb 06, 2002
Posts: 22
Have a look at the code below
public class DivisionByZero3 {
public void division() {
int num1 = 10;
int num2 = 0;
try {
int t= num1/num2 ;
return;
}
catch (ArithmeticException e) { // (2)
System.out.println("Dealt with " + e);
System.out.println("catch.");
System.exit(1);

}
finally { // (3)
System.out.println("Finally done.");
}
System.out.println("Returning from division."); // (4)
}
public static void main(String args[]) {
new DivisionByZero3().division();
System.out.println("Returning from main.");
}
}
Here the finally block does not execute.
Is there any other way to ensure the finally
block does not execute ..
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Murgan Sub:
Is there any other way to ensure the finally
block does not execute ..

The only way a finally block will not execute is if the thread executing that try/catch/finally segment terminates before it can run. In the case you've shown, the thread terminates because of the call to System.exit(). The thread might also be terminated in the case that it is a daemon thread and all user threads end. As far as I know, the only way in which a finally block won't execute is due to the prior termination of the thread.
I hope that helps,
Corey


SCJP Tipline, etc.
Tarik Makota
Greenhorn

Joined: Jan 29, 2002
Posts: 23
yes:
-exception arrising in finnaly
-shuting down your PC
-thread dies
-and as you indicated System.exit()
As you can see only controlable way is using System.exit().
Tarik
chafule razgul
Ranch Hand

Joined: Feb 09, 2002
Posts: 63
If you remove the System.exit(1); in the catch clause or replace it with a return statement then your finally block will be executed. If you rethrow the exception in the catch clause the finally block will also be executed. I'm not sure where exactly in the JLS it is, but i'm pretty sure you can find it there
hope this helps
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
here it is
14.19 The try statement


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Preventing finally Block from execution ...