jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes nested try catch finally in a for loop : how does it work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "nested try catch finally in a for loop : how does it work" Watch "nested try catch finally in a for loop : how does it work" New topic
Author

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

rijagu chan
Greenhorn

Joined: Apr 10, 2000
Posts: 7
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
Uvnik Gupta
Ranch Hand

Joined: Jul 24, 2000
Posts: 32
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

Joined: Apr 10, 2000
Posts: 7
Thanks Uvnik. I understand it now.
 
Consider Paul's rocket mass heater.
 
subject: nested try catch finally in a for loop : how does it work