我试图了解如何使用java异常处理在输入无效时返回异常消息。据我所知,我必须使用try catch返回,以便编译(或两者)。但实际上,如果输入参数无效,我不想返回任何内容。
如果我正在处理字符串,则会出现空值。但这似乎与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));
}
}
这段代码我没有多大意义,但我想了解如何处理一般情况。
答案 0 :(得分:1)
您必须返回一些值(必须是int)。使用字符串你没有这样的问题,因为String不是标准数据类型,因此可以是Null。但是在这里你必须在catch语句中返回一些值。
答案 1 :(得分:1)
目前您的arrayGet无法编译。如果要在出现错误时返回String,可以在arrayGet的catch块中执行此操作,如
} catch (ArrayIndexOutOfBounds e) {
throw new Exception("my message");
}
主要方法
try {
int i = arrayGet(11);
} catch (Exception e) {
String msg = e.getMessage();
}
答案 2 :(得分:1)
int
和String
的常见超类型是Object
(装箱后)。这意味着如果您将返回类型声明为String
,则可以返回int
或Object
:
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];
}