Why we must handle exception for method not throwi

2019-08-26 07:43发布

问题:

This question already has an answer here:

  • use of exception in inheritance 6 answers

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.

回答1:

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
}