首页 > 解决方案 > 尝试捕获 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 以在屏幕上显示消息?

标签: javaarrayssortingnulltry-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 块。


推荐阅读