Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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.
 
Time is mother nature's way of keeping everything from happening at once. And this is a tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic