簡體   English   中英

Java異常處理不返回任何值

[英]Java exception handling returning no value

我試圖了解如何在輸入無效時使用Java異常處理僅返回異常消息。 據我了解,我必須使用try catch之外的return來進行編譯(或同時進行編譯)。 但是實際上,如果輸入參數無效,我不想返回任何內容。

如果我正在處理字符串,則將為null。 但這似乎不適用於int。

沒辦法嗎?

public class Arrays {

public static int[] intArray = {1,2,3,4,5,60,7,8,9,10};


public static int arrayGet(int[] array, int i){
    try{
        return intArray[i];

    }
    catch (ArrayIndexOutOfBoundsException e){
        System.out.println("Please enter number between 0 and "+i);
    }
}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(arrayGet(intArray,11));
}
}

該代碼沒有多大意義,但我想了解如何處理一般情況。

您將必須返回一些值(必須為int)。 使用Strings不會遇到這樣的問題,因為String不是Standard數據類型,因此可以為Null,但是在這里您必須在catch語句中返回一些值。

目前,您的arrayGet無法編譯。 如果要在發生錯誤的情況下返回String,可以在arrayGet的catch塊中執行此操作

} catch (ArrayIndexOutOfBounds e) {
    throw new Exception("my message");
}

而在主要方法

try {
    int i = arrayGet(11);
} catch (Exception e) {
    String msg = e.getMessage();
}

intString的常見超級類型是Object (裝箱后)。 這意味着如果您將返回類型聲明為Object則可以返回Stringint

public static Object arrayGet(int[] array, int i){
    try{
        return intArray[i];    
    }
    catch (ArrayIndexOutOfBoundsException e){
        System.out.println("Please enter number between 0 and "+i);
        return e.getMessage();
    }
}

但是調用者將不知道返回了哪種類型,因此他們只能將其真正用作Object

Object o = arrayGet(array, 11);
// o is maybe an int, or maybe a String. But it's definitely an Object.

在這種情況下,方法的參數是罪魁禍首。 讓調用者知道的一種方法是拋出IllegalArgumentException

public static int arrayGet(int[] array, int i){
    if(i < 0 || i >= array.length)
        throw new IllegalArgumentException("Please enter number between 0 and " + i);

    return intArray[i];
}

暫無
暫無

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

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