Java 如何将异常传递给构造函数?
我四处搜索,但不知道怎么做Java 如何将异常传递给构造函数?,java,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{
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
传递给构造函数?我真的不知道怎么做。抛出新的NoSuchUserException(id,new ArrayIndexOutOfBoundsException())
你的意思是吗?看看异常中的构造函数-你向超类异常的构造函数中给出了原因:
public class FooException extends Exception
{
public FooException( int id, Throwable cause )
{
super( "user " + id + " not found", cause );
}
}
在代码中,您可以这样使用:
public void method( int id ) throws FooException
{
try
{
someMethodThatThrows();
}
catch ( ArrayIndexOutOfBoundsException e )
{
throw new FooException( id, e );
}
}
private void someMethodThatThrows()
{
throw new ArrayIndexOutOfBoundsException();
}
try块“查看”抛出的每个异常,如果是
ArrayIndexOutOfBoundsException
则跳入catch块-在那里,您可以抛出自己的异常,并将ArrayIndexOutOfBoundsException
作为原因。您能解释一下您试图实现的目标吗?通过阅读标题和代码,我不清楚。super(“User+id+”not found”);
这怎么可能连编译方法都告诉我你有更深层次的设计缺陷。你是说类似于抛出新的NoUserException(id,e)
?我认为这里抛出可能是为了演示目的,比如“这个异常在这里抛出”