Forums Register Login

try/catch

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
hi,Thejus/Mahesh,
got it now, thank for your detailed expl.
simon
Skool. Stay in. Smartness. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 826 times.
Similar Threads
somebody pls explain why this code does not give an exception
exceptions
nested try catch finally in a for loop : how does it work
Exception HAndling
try-catch-finally
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 02:12:34.