Another cert question, can anybody break this down?
Marilyn added code tags
[This message has been edited by Marilyn deQueiroz (edited April 20, 2001).]
sai challa
Ranch Hand
Joined: Feb 06, 2001
Posts: 54
posted
0
Originally posted by Otto Deckelman: Another cert question, can anybody break this down? class Question { 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; }finnaly{ ++i; } }catch (Exception outer) { i += 3; }finally{ ++i; } } } }
1.the for loop starts with i=0.It enters the first outer try block,and checks the condition i%3 i.e 0%3 =0,since the if condition is true ,an Exception("EO") is thrown,the control now goes to a catch block handling the exception and the inner try block is not entered.The catch block(Exception outer) handles the exception produced and i is incremented by 3 i.e i=0+3=3.The finally block is always executed and i is incremented again i.e i=3+1=4 Now control goes to the for loop ,since i<10 i is incremented by 1 i.e i=4+1=5. 2.Now the outer try block is entered i%3 i.e 5%3=2 which is not equal to 0.Hence if condition is skipped and control is transferred to the next statement i.e the inner try block here i%3 is evaluated i.e 5%3=2 which is not equal to 1 ,hence the if condition is skipped and control goes to the next statement and the value of i i.e 5 is printed. The finally block is always executed ,hence the inner finally block increments i to 6 and the outer finally block increments i to 7. 3.Now control comes to the for loop again and i is incremented to 8.Since i<10 ,the outer try block is entered i%3 is evaluated i.e 8%3=2 which is not 0,hence the inner try block is entered again i%3 is evaluated i.e 8%3=2 which is not equal to 1,the if condition is skipped and the next statement is executed which prints the value of i i.e 8. The finally block is always executed ,hence i is incremented to 9 in the inner finnaly block and 10 in the outer finally block . 4.Now the control goes to the for loop with i=10 ,therefore the condition i<10 fails and control goes out of for loop. Hence output is 5,8