簡體   English   中英

如何將異常傳遞給構造函數?

[英]How to pass exception to the constructor?

我四處尋找,但不知道如何做到這一點

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傳遞給構造函數? 我真的不知道該怎么做。

查看異常中的構造函數 - 您將原因提供給超類 Exception 的構造函數:

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作為原因拋出您自己的異常。

throw new NoSuchUserException(id, new ArrayIndexOutOfBoundsException());

你是那個意思嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM