Why we must handle exception for method not throwing exceptions? [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 06:21:41

问题


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
}


来源:https://stackoverflow.com/questions/17170583/why-we-must-handle-exception-for-method-not-throwing-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!