Why we must handle exception for method not throwi

2019-08-26 07:34发布

This question already has an answer here:

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条回答
贼婆χ
2楼-- · 2019-08-26 08:37

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
}
查看更多
登录 后发表回答