0

与えられた

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();
   }

  }

(a.process()) 行で例外を処理する必要があるのはなぜですか?.クラス B のメソッド process は例外をまったくスローしません。PS:これは SCJP の質問です。

4

1 に答える 1

4

Bインスタンスを type の変数に割り当てましたAA.process()例外がスローされるため、コードでその可能性を処理する必要があります。

Asを受け入れる別のメソッドにインスタンスを渡すとします。

public void doSomething(A a) {
  a.process; // <--- we don't know this is a B, so you are forced to 
             //      catch the exception
}
于 2013-06-18T13:49:13.333 に答える