Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Preventing finally Block from execution ...

 
Murgan Sub
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tarik Makota
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here it is
14.19 The try statement
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic