File size: 1,384 Bytes
0284885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package Exception_package2;

public class Exception_demo5 {
    public static void main(String[] args) {
        /*
            throws:写在方法定义处,表示声明一个异常。告诉调用者,使用本方法可能会有哪些异常
            throw:写在方法内,结束方法。手动抛出异常对象,交给调用者。方法中下面的代码不再执行了。

            需求:
                定义一个方法求数组最大值
         */

        int[] arr = null;
        int max = 0;

        try {
            max = getMax(arr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(max);
    }

    private static int getMax(int[] arr) throws NullPointerException, ArrayIndexOutOfBoundsException {
        if (arr == null) {
            //手动创建一个异常对象,并把这个异常交给方法的调用者处理
            //此时方法就会结束,下面的代码不会再执行了
            throw new NullPointerException();
        }

        if (arr.length == 0) {
            throw new ArrayIndexOutOfBoundsException();
        }

        System.out.println("看看我执行了吗?");
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
}