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

try/catch

 
Simon Xu
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I couldnt trace below for loop, please help why the output is 5, 8? How does throw new Eception work? Thanx
for (int i=0; i<10; ++i){
try{
if (i%3==0) throw new Exception ("E");
try{
if (i%3==1) throw new Exception ("E");
System.out.println(i);
} catch (Exception inner) {i *=2;}
finally {++i;}
}catch (Exception Outer) {i +=3;}
finally (++i;}
}
}
}catch
 
Raghavendra Holla
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Try code given below, you will get the logic.
for(int i=0; i<10; ++i)
{
try{
if (i%3==0) throw new Exception ("E");
try{
if (i%3==1) throw new Exception ("E");
System.out.println(i);
}
catch (Exception inner) {i *=2;}
finally {System.out.println(i);++i;}
}
catch (Exception Outer) {i +=3;}
finally {System.out.println(i);++i;}
}
}

---
This is because "finally" will be executed eventhough no exception.
-
rvholla.
 
thejus/mahesh
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Simon,
It is very interesting question
I would like to explain in steps
step1 in forloop i get initialised to 0;
step2 excetion 0%3==0 is encountered exception outer is caught
step3 i get incremented to 3;
step4 finally bloc after catch get executed so now i=4;
step5 in forloop i gets incremented to 5;
step6 none of the try will throw exception
so 5 will be printed after inner if loop
step7 in first finally bloc i gets incremented to 6
step8 in second finally i gets incremented to 7
step9 in for loop i gets incremented to 8
step6 is repeated with i=8;
step7 i=9;
step8 i=10
step10 forloop fails
hope it is clear by now
 
Simon Xu
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,Thejus/Mahesh,
got it now, thank for your detailed expl.
simon
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic