• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

try/catch

 
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,Thejus/Mahesh,
got it now, thank for your detailed expl.
simon
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic