Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help, flowing program

 
michelle
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Test {
public static void main(String args[]) {
for (int i=0; i<10; ++i) {
try {
if(i%3==0) throw new Exception("E0");
try {
if(i%3==1) throw new Exception("E1");
System.out.println(i);
} catch (Exception inner) {
i*=2;
} finally {
++i;
}
} catch (Exception outer) {
i+=3;
} finally {
++i;
}
}
}
}
output: 5,8
if earse inner try-catch output will be 5,7
if inner try-catch only will output 0,2
I can't got it, please help?
 
Farhan Tariq
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peli!
You have to clear your mind about inner outer try blocks. If exception occured in outer try block the catch block of outer will be in consideration and skip the whole inner block even inner finally too. So in your program first the value of i = 0, that raises exception because of "0%3". So outer catch block starts execution and increment 3 in i, and then finally increment in i too after wards when loop again starts the value of i = 5 because one loop increment too.
Now 5%3 != 0 so no exception raised then 5%3 != 1 too so skip this too and print the value of i to console, which is 5.
Then finally of inner class executes which increment in i and outer finally too now i = 7 and last increment through the loop so again the loop starts with the value of i = 8.
first if skip then second if skip and print 8. Next time i will be 11 so loop break. And you have 5 and 8 printed on your console window.
Now try to think about other reasons in this manner and if still having difficulty, try to print the value of i after each line so you can understand the behavior of try structure.
Regards
Farhan
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi peili,
Thought this looked familiar .. it's one of Jaworski's questions, right
Here's the code again and an example of how you can walk through it:

The important point to remember is that 'finally' blocks are executed regardless of wether or not an exception is thrown. The only time a finally block will not execute is if an earlier catch block calls System.exit().
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
[This message has been edited by Jane Griscti (edited June 17, 2001).]
 
michelle
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, farhan and Jane.
I think I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic