Reputation: 1
I'd been trying to set ArrayIndexOutOfBoundsException
as cause of NoSuchUserException
(for MyUser.class),but it doesn't work. The Throwable
parameter represents the cause of the exception. Can someone tell me what am I missing?
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("");
}
}
Upvotes: 0
Views: 1337
Reputation: 9093
You can simply pass the cause to the parent constructor:
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;
}
}
See the documentation.
Upvotes: 2