2015-10-23 2 views
0

Я пытался установить ArrayIndexOutOfBoundsException как причину NoSuchUserException (для MyUser.class), но это не работает. Параметр Throwable представляет причину исключения. Может ли кто-нибудь сказать мне, что мне не хватает?Установить причину для пользовательского исключения

public class NoSuchUserException extends Exception { 
     private int id = 0; 
     private Throwable cause; 
      public NoSuchUserException(int id, Throwable x) { 
      super("User " + id + " does not exist"); 
      this.cause = x; 
     } 
    } 

    import java.util.Arrays; 
    public class MyUser { 
     private String[] users; 

     public MyUser(String[] users) { 
      this.users = Arrays.copyOf(users, users.length); 
     } 

     public String getUser(int id) throws NoSuchUserException { 
      try { 
       someMethodThatThrows(); 
      } catch (ArrayIndexOutOfBoundsException e) { 

       throw new NoSuchUserException(id, e); 
      } 

      return users[id]; 
     } 

     private void someMethodThatThrows() { 
      throw new ArrayIndexOutOfBoundsException(""); 
     } 
    } 

ответ

2

Вы можете просто передать дело на родительский конструктор:

public class NoSuchUserException extends Exception { 
    public int id = 0; 
    public NoSuchUserException(int id, Throwable x) { 
     super("User " + id + " does not exist", x); 
     this.id = id; 
    } 
} 

См the documentation.

Смежные вопросы