Why should we handle an exception for a method that excludes exceptions?

Considering

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 should we handle the exception in the string (a.process ())? Does a class B method process throw an exception at all? PS: This is a SCJP question.

0
source share
1 answer

You have assigned your instance to Ba type variable A. Since it A.process()throws an exception, your code should handle this feature.

Imagine passing your instance to another method that takes As:

public void doSomething(A a) {
  a.process; // <--- we don't know this is a B, so you are forced to 
             //      catch the exception
}
+3
source

All Articles