gpt4 book ai didi

java - try catch null 和空数组

转载 作者:行者123 更新时间:2023-12-02 01:05:22 24 4
gpt4 key购买 nike

我正在尝试在我制作的方法中执行异常捕获:

public static int[] sort(int[] array) {
if (array.length == 1) {
return array;
}
int[] arrayToSort = array.clone();
for (int i = 0; i < arrayToSort.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arrayToSort.length; j++) {
if (arrayToSort[j] < array[i]) {
if (arrayToSort[j] < arrayToSort[minIndex])
minIndex = j;
}
}
if (i != minIndex) {
Swap.selectionSwap(arrayToSort, minIndex, i);
}
}
return arrayToSort;
}

我想验证并捕获以下异常:1) 数组长度等于02) 数组内为 null

我尝试在方法开始时执行此操作:

      try {
if(array.length == 0);
} catch (ArrayIndexOutOfBoundsException exceptionForAnEmptyArray) {
System.out.println("an array need to be filled");
}
try {
array.equals(null);
}
catch (NullPointerException e) {
System.out.println("An array should contain the numbers");
}

空数组已通过验证,但消息未出现。与空相同。尝试在数组内使用 Inter.parseInt 解析 null 。我需要如何修改 try catch 以便在发生异常时在屏幕上显示消息?

最佳答案

您误解了它的工作原理。如果您想做一些事情来响应表达式为真,那么异常是不相关的并且不会帮助您。尝试这样的事情:

if (array.length == 0) System.out.println("An array need to be filled");

或者,先做你的事情,然后再响应问题 - 导致问题的语句放入 try 中,并且不需要检查表达式:

try {
System.out.println("The first item is " + array[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An array need to be filled");
}

这里的array[0]表达式在执行时会抛出该异常。因为它发生在 try block 内,所以执行会跳转到匹配的 catch block 。

关于java - try catch null 和空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60126573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com