有 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{
        try{
            throw new NoSuchUserException(id, throw ArrayIndexOutOfBoundsException here);
        } catch (ArrayIndexOutOfBoundsException e) {

        }
        return id;
    }
}

如何将ArrayIndexOutOfBoundsException传递给构造函数?我真的不知道怎么做


共 (2) 个答案

  1. # 1 楼答案

    查看异常中的构造函数-将原因输入到超类异常的构造函数中:

    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

  2. # 2 楼答案

    抛出新的NoSuchUserException(id,new ArrayIndexOutOfBoundsException())

    你是这个意思吗