2014-09-06 3 views
0

다음 진술은 "파생 클래스 생성자가 기본 클래스 생성자가 던진 예외를 catch 할 수 없습니다." 그러나 나는 그것을 잡을 수있다. 누구나 내가 잘못 된 곳을 설명 할 수 있습니까?"파생 클래스 생성자는 기본 클래스 생성자가 던진 예외를 catch 할 수 없습니다." 하지만 그것을 잡을 수있다

class Base { 
    Base() throws CloneNotSupportedException { 
     throw new CloneNotSupportedException(); 
    } 
} 

class Derived extends Base { 

    Derived() throws CloneNotSupportedException, RuntimeException {} 

    public static void main(String[] args) { 
     try { 
      Derived d = new Derived(); 
     } 
     catch(CloneNotSupportedException e) { 
      e.printStackTrace(); 
     } 
     catch(RuntimeException re){} 
    } 
} 

출력 : 당신은 파생 클래스의 생성자에서 아무것도 잡기되지 않습니다

java.lang.CloneNotSupportedException 
    at Base.<init>(Coffee.java:4) 
    at Derived.<init>(Coffee.java:9) 
    at Derived.main(Coffee.java:14) 

답변

2

. main 메서드에서 예외를 catch합니다. 따라서 귀하가 게시 한 견적과 모순되지 않습니다.

Derived() { 
    try { 
    super(); 
    } catch (CloneNotSupportedException e) { 
    System.out.println("We have indeed caught an exception from the "+ 
      "base-class constructor! The book was wrong!"); 
    } 
} 

이 그것을 시도하고 나오는 것을 참조 :

1

여기에 파생 클래스의 생성자가 기본 클래스 생성자에서 예외를 잡기 위해 봐야 할 방법은 다음과 같습니다.

+0

책이 맞습니다. 내가 파생 한 수업을 수정했을 때. 그것은 나에게 complie 시간 오류를 준다 "super에 대한 호출은 생성자의 첫 번째 문장이어야한다."그래서 우리는 그 예외를 잡을 수 없다고 짐작한다. – user2899676

+1

정확하게 나의 대답의 요점. 배우는 가장 좋은 방법은 자신을 찾는 것입니다. –

관련 문제