设置自定义异常的原因

时间:2015-10-23 21:08:43

标签: java

我一直试图将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("");
        }
    }

1 个答案:

答案 0 :(得分: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