• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

nested try catch finally in a for loop : how does it work

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please explain : the answer for this when I run is 5 and 8. Thanks very much.
for(int i = 0; i<10; ++i) {
try { //outer try
if ( i % 3 == 0 ) throw new Exception("outer");
// inner try catch finally

try {
if ( i % 3 == 1) throw new Exception("inner");
System.out.println(i);
} catch (Exception inner) {
i*=2;
} finally {
++i;
} // end inner catch finally


} catch (Exception outer) { // catch outer
i +=3;
} finally {
++i;
} // end outer finally
} // end for
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the first iteration : i = 0 hence i%3 == 0 => true => Exception Outer => i = i + 3 (in catch) => i++ (in finally) => i = 5 for next iteration of for loop => prints this value => i++ (in inner finally) => i++ (in outer finally) => i++ for next iteration of for loop => print 8 => i++ (in inner finally) => i++ (in outer finally) => i++ for next iteration of for loop => i == 11 which is greater than 10 => break loop.
Remember finally is always executed
 
rijagu chan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Uvnik. I understand it now.
reply
    Bookmark Topic Watch Topic
  • New Topic