2014-04-08 2 views
2
package Exception; 

public class Exceptions { 
    public class NoSpaceException extends RuntimeException { 
     public NoSpaceException(){ 
      super("There is not enough room in the set for another element."); 
     } 
    } 

    public class NotValidTypeException extends NullPointerException { 
     public NotValidTypeException(){ 
      super("You can only add strings to a set."); 
     } 
    } 

    public class NoItemException extends NullPointerException { 
     public NoItemException(){ 
      super("There is no next element."); 
     } 
    } 
} 

다른 클래스에는이 패키지에 대한 가시성이 없습니다. 나는이 예외 중 하나를 던질 수있는 다른 세 가지 클래스를 가지고 있으며, sans 패키지 선언 위에있는 코드를 각 파일에 복사/붙여 넣기하고 싶지 않습니다. 중복을 줄이고 별도의 파일로 만들고 싶습니다.예외 클래스 생성; 다른 클래스의 비 가시성

어떻게 볼 수 있습니까?

+0

예외 클래스를 공용으로 설정하면 액세스 할 수 있습니다. – chathux

+0

@chathux, 공개입니다. – gator

+0

다른 클래스에서도 볼 수 있어야합니다. 나는 그것이 왜 보이지 않는지 이해하지 못한다. – chathux

답변

3

어느 것으로 내부 클래스를 변경 정적, 즉 :

public class Exceptions { 
    public static class NoSpaceException extends RuntimeException { 
     ... 
    } 

    public static class NotValidTypeException extends RuntimeException { 
     ... 
    } 

    public static class NoItemException extends RuntimeException { 
     ... 
    } 
} 

당신은 아무것도 변경하지 않는 경우 또는, 당신은 예외의 인스턴스를 통해 인스턴스를 만들 수 있습니다

Exceptions exceptions = new Exceptions(); RuntimeException e = exceptions.new NoItemException();

첫 번째 방법이 바람직합니다.

참고로 RuntimeException보다 구체적인 클래스를 확장하는 것을 고려하십시오 (예 : IllegalArgumentException, IllegalStateExecption 등).