java如何将异常传递给构造函数?
我四处搜索,但不知道怎么做
public class NoUserException extends Exception {
public NoUserException(int id, Throwable cause){
super("User" +id + " not found");
}
}
public class User {
public int getUserID(int id) throws NoUserException{
try{
throw new NoSuchUserException(id, throw ArrayIndexOutOfBoundsException here);
} catch (ArrayIndexOutOfBoundsException e) {
}
return id;
}
}
如何将ArrayIndexOutOfBoundsException
传递给构造函数?我真的不知道怎么做
# 1 楼答案
查看异常中的构造函数-将原因输入到超类异常的构造函数中:
在代码中,您可以这样使用:
try块“查看”抛出的每个异常,如果它是
ArrayIndexOutOfBoundsException
,则跳入catch块-在那里,您可以抛出自己的异常,原因是ArrayIndexOutOfBoundsException
# 2 楼答案
抛出新的NoSuchUserException(id,new ArrayIndexOutOfBoundsException())
你是这个意思吗