0

Given

public class ToBeTestHandleException{

static class A {
    void process() throws Exception {
        throw new Exception();
    }
  }

static class B extends A {
    void process() {
        System.out.println("B ");
    }
   }



public static void main(String[] args) {
    A a = new B();
    a.process();
   }

  }

Why we should handle the exception at line (a.process()) ?.The method process of class B does not throw exception at all? PS:This is an SCJP question.

BenMansourNizar
  • 1,558
  • 4
  • 21
  • 42

1 Answers1

4

You've assigned your B instance to a variable of type A. Since A.process() throws the exception, your code needs to handle that possibility.

Imagine you pass your instance to another method that accepts As:

public void doSomething(A a) {
  a.process; // <--- we don't know this is a B, so you are forced to 
             //      catch the exception
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254