• 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

About Exception Handling.....

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can somebody explain the flow of the following code ?
why it result in 4 and 5....
thx...^_^
class Question1 {
public static void main(String[] args) {
for(int i=0;i<10;++i) {
try {
try {
if(i%3==0) throw new Exception("E0");
System.out.println(i);
}catch (Exception inner) {
i*=2;
if(i%3==0) throw new Exception("E1");
}finally{
++i;
}
}catch (Exception outer) {
i+=3;
}finally{
--i;
}
}
}
}
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
jellyman,
Welcome to Javaranch
Please read the Javaranch Naming Policy and change your publicly displayed name to comply with our unique rule. Thank you for your cooperation.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The flow of the program is as such
1. for loop i = 0
2. i%3 is 0 Goes to Exception handler inner
3. Exception handler inner
i *= 2 is 0
i%3 is 0 goes to Exception handler outer
finally for inner try
++i is 1
4. Exception handler outer
i+=3 is 4
finally for outer try
--i is 3
5. for loop i = 4 (i will be incremented by one and check i<10 true
6. i%3 is not equal to 0 so print 4
7. Inner try finally ++i is 5
8. Outer try finally --i is 4
9. for loop i = 5 (i will be incremented by one and check i<10 true)
10. i%3 is not equal to 0 so print 5
11. Inner try finally ++i is 6
12. Outer try finally --i is 5
13. for loop i = 6 (i will be incremented by one and check i<10 true)
14. i%3 is 0 now the program flow is as such from 1-4
15. for loop i =16 so the loop ends
Hope this will help u understand the program flow and explains why the program prints 4 and 5
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic