Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 设置自定义异常的原因_Java - Fatal编程技术网

Java 设置自定义异常的原因

Java 设置自定义异常的原因,java,Java,我一直试图将ArrayIndexOutOfBoundsException设置为NoSuchUserException(对于MyUser.class)的原因,但它不起作用。Throwable参数表示异常的原因。有人能告诉我我错过了什么吗 public class NoSuchUserException extends Exception { private int id = 0; private Throwable cause; publi

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

您只需将原因传递给父构造函数:

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