LOADING

正在加载喵~

week6

2025/3/29 未来与梦 未标记

[collapse title”第一题(点击打开)”] java public class Ex5_1 { public static void main(String[] args) { try { int num[] new int[10]; System.out.println(“num[10] is “ + num[10]); } catch (Ar…

[collapse title=”第一题(点击打开)”]

public class Ex5_1 {
    public static void main(String[] args) {
        try {
            int num[] = new int[10];
            System.out.println("num[10] is " + num[10]);
        } catch (ArrayIndexOutOfBoundsException ex) {
            System.out.println("ArrayIndexOutOfBoundsException");
        } catch (ArithmeticException ex) {
            System.out.println("ArithmeticException");
        } catch (RuntimeException ex) {
            System.out.println("RuntimeException");
        } catch (Exception ex) {
            System.out.println("Exception");
        }
    }
}    

[/collapse]

[collapse title=”第二题”]

public class Ex5_2 {
    // IllegalArgumentException异常的声明
    static double cal(double a, double b) throws IllegalArgumentException {
        double value;
        if (b == 0) {
            // 抛出IllegalArgumentException异常,并定义消息字符串为“除数不能为0”
            throw new IllegalArgumentException("除数不能为0");
        } else {
            value = a / b;
            if (value < 0) {
                // 抛出IllegalArgumentException异常,并定义消息字符串为“运算结果小于0”
                throw new IllegalArgumentException("运算结果小于0");
            }
        }
        return value;
    }

    public static void main(String[] args) {
        double result;
        try {
            double a = Double.parseDouble(args[0]);
            double b = Double.parseDouble(args[1]);
            result = cal(a, b);
            System.out.println("运算结果是: " + result);
        } 
        // 处理IllegalArgumentException异常
        catch (IllegalArgumentException e) {
            System.out.println("异常说明: " + e.getMessage());
        }
    }
}    

[/collapse]