簡體   English   中英

從void返回字符串

[英]Return a string from void

你好,我有這個程序設計任務,在這里我必須使用他們給我們使用的函數,因為它們給我們使用,我遇到的問題是這必須是無效的,而且我不允許使用System.out。 println(); 還是我的問題是如何在不更改方法標頭的情況下返回異常,還是使用System.out.println();?

public void deleteItem(String itemID){
    try {
        index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);
    }
    catch (IndexOutOfBoundsException e) {
        System.out.println("ITEM " + itemID + " DOES NOT EXIST!");
    }
}

您可以更改方法簽名並引發異常

public void deleteItem(String itemID) throws Exception{
    try {
        index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);
    }catch (IndexOutOfBoundsException e) {
        Exception ex = new Exception("ITEM " + itemID + " DOES NOT EXIST!");
        throw ex;
    }
}

完成后,您會收到如下錯誤消息

try{
    xxx.deleteItem("your itemID");
}catch(Exception e){
    // You will read your "ITEM " + itemID + " DOES NOT EXIST!" here
    String yourErrorMessage = e.getMessage();
}
public void deleteItem(String itemID){
    try {
        index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);
    }
    catch (IndexOutOfBoundsException e) {
        throw new IndexOutOfBoundsException( "ITEM " + itemID + " DOES NOT EXIST!");
    }
}


    public void deleteItem(String itemID)throws IndexOutOfBoundsException{

        index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);

   } 

您不能返回異常。 從方法拋出異常,您可以為此使用關鍵字throw 。嘗試上述方法從方法拋出異常

在您的catch塊中執行以下操作:

catch (IndexOutOfBoundsException e) {
       throw new IndexOutOfBoundsException("ITEM " + itemID + " DOES NOT EXIST!");
}

由於IndexOutOfBoundsException是RuntimeException,因此不需要在方法中添加throw聲明。

無論在哪里調用該函數,都可以添加catch塊來讀取錯誤消息,如下所示:

catch (IndexOutOfBoundsException ex) {
      System.out.println(ex.getMessage());
}

好吧,如果該方法使用不正確(未經索引驗證),也許應該拋出異常?

您可以完全刪除try-catch塊。 IndexOutOfBoundsException是運行時異常,因此它不需要throws IndexOutOfBoundsException語法。

但是,如果您希望該異常不那么隱秘,則可以使用自己的RuntimeException對其進行包裝:

public void deleteItem(String itemID){
    try {
        index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);
    }
    catch (IndexOutOfBoundsException e) {
        throw new RuntimeException("Invalid item ID: " + itemID, e);
    }
}

刪除try..catch塊並將您的功能修改為

public void deleteItem(String itemID) throws IndexOutOfBoundsException{
         index = Change.indexOf(itemID);
        StockItems.remove(index);
        Change.remove(index);
}

在嘗試調用此方法的地方添加try catch並使用System.out.println("ITEM " + itemID + " DOES NOT EXIST!"); 那里。

即使您沒有向該方法添加拋出,而是將deleteItem的調用放在try catch塊中,也可以。

暫無
暫無

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

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