R
Rodusa
I am a beginner in java and I am having difficulty in understanding
the output below which uses exceptions and recursion. So far I was
able to understand the logic until line 10. After that I am lost. I
don't understand why is i being decremented? first it printed rec 1,
rec 2 , rec 3 and when it reached the exception it started to
decrement i like 3, 2, 1.
Rod
Output:
1. A(int)
2. B(int)
3. A()
4. B()
5. C()
6. 2
7. rec 1
8. rec 2
9. rec 3
10. Foo excepted
11. Handled in C -> i:3
12. Finally
13. Handled in C -> i:2
14. Finally
15. Handled in C -> i:1
16. Finally
17. Handled in Main
class A{
int x;
public A(){
x=2;
System.out.println("A()");
}
public A(int x){
this.x = x;
System.out.println("A(int)");
}
public void print(){
System.out.println(x);
}
}
class B extends A{
int x;
public B(){
x=5;
System.out.println("B()");
}
public B(int x){
super(x);
x=5;
System.out.println("B(int)");
}
public void foo() throws Exception{
System.out.println("Foo excepted");
throw new Exception();
}
}
class C extends B{
int x;
public C(){
x=1;
System.out.println("C()");
}
public void rec(int i) throws Exception{
System.out.println("rec " + i);
try{
if(i==3)
foo();
else
rec(i+1);
} catch(Exception e){
System.out.println("Handled in C -> i:" +i);
throw e;
} finally {
System.out.println("Finally");
}
}
}
class Main{
public static void main(String[] args){
try{
B b = new B(3);
C c = new C();
c.print();
c.rec(1);
} catch (Exception e){
System.out.println("Handled in Main");
}
}
}
the output below which uses exceptions and recursion. So far I was
able to understand the logic until line 10. After that I am lost. I
don't understand why is i being decremented? first it printed rec 1,
rec 2 , rec 3 and when it reached the exception it started to
decrement i like 3, 2, 1.
Rod
Output:
1. A(int)
2. B(int)
3. A()
4. B()
5. C()
6. 2
7. rec 1
8. rec 2
9. rec 3
10. Foo excepted
11. Handled in C -> i:3
12. Finally
13. Handled in C -> i:2
14. Finally
15. Handled in C -> i:1
16. Finally
17. Handled in Main
class A{
int x;
public A(){
x=2;
System.out.println("A()");
}
public A(int x){
this.x = x;
System.out.println("A(int)");
}
public void print(){
System.out.println(x);
}
}
class B extends A{
int x;
public B(){
x=5;
System.out.println("B()");
}
public B(int x){
super(x);
x=5;
System.out.println("B(int)");
}
public void foo() throws Exception{
System.out.println("Foo excepted");
throw new Exception();
}
}
class C extends B{
int x;
public C(){
x=1;
System.out.println("C()");
}
public void rec(int i) throws Exception{
System.out.println("rec " + i);
try{
if(i==3)
foo();
else
rec(i+1);
} catch(Exception e){
System.out.println("Handled in C -> i:" +i);
throw e;
} finally {
System.out.println("Finally");
}
}
}
class Main{
public static void main(String[] args){
try{
B b = new B(3);
C c = new C();
c.print();
c.rec(1);
} catch (Exception e){
System.out.println("Handled in Main");
}
}
}