java - 尝试捕获 null 和空数组
问题描述
我正在尝试在我制作的方法中执行异常捕获:
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)数组长度等于 0 2)数组内的 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");
或者,只需执行您的操作,然后在 AFTERward 之后响应问题 - 导致问题的语句在 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 块中,所以执行跳转到匹配的 catch 块。
推荐阅读
- python - Python 和 Selenium 的授权异常
- oracle - 在存储过程 PL/SQL 中使用绑定变量
- html - 如何对齐两个固定的div?实时聊天和 cookie 法律协议示例
- jquery - jquery find all elements with the same class, stop after all found
- mysql - Mysql 更新自加入,根据组增加列值
- xml - Microsoft Project Plan in xml format
- dynamics-crm - Dynamics 365 拖放附件
- python - Replace Dataframe column name
- swift - File access to image files on camera roll (iOS 12.1.4, Swift 4.2, Xcode 10.1)
- r - 如何在 plotly 或 ggplot 中绘制具有极其广泛分布的值/间隙的直方图