wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes try/catch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "try/catch" Watch "try/catch" New topic
Author

try/catch

Simon Xu
Ranch Hand

Joined: Aug 16, 2000
Posts: 235
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

Joined: Jun 02, 2000
Posts: 58
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

Joined: Aug 21, 2000
Posts: 19
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

Joined: Aug 16, 2000
Posts: 235
hi,Thejus/Mahesh,
got it now, thank for your detailed expl.
simon
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try/catch
 
Similar Threads
Exception HAndling
try-catch-finally
somebody pls explain why this code does not give an exception
nested try catch finally in a for loop : how does it work
exceptions