黑马程序员技术交流社区

标题: 关于用try和catch解决多个异常的一点疑惑,求解答…… [打印本页]

作者: 王盟    时间: 2015-8-30 21:38
标题: 关于用try和catch解决多个异常的一点疑惑,求解答……
请看下面代码,其中method2,完全不能达到method1的效果。method1不会卡顿,一直运行到打印over,但是method2卡在第一个错误,停止了。那么是不是说,多个错误不能使用method2的方法?

public class ExceptionDemo2 {
    public static void main(String[] args) {
        method1();
        method2();
    }

    // 针对每一个异常写一个try...catch代码。
    public static void method1() {
        int a = 10;
        int b = 0;
        try {
            System.out.println(a / b);// ArithmeticException
            System.out.println("hello");
        } catch (ArithmeticException ae) {
            System.out.println("除数不能为0");
        }
        int[] arr = { 1, 2, 3 };
        try {
            System.out.println(arr[3]);// ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException ae) {
            System.out.println("数组越界异常");
        }
        // 继续操作
        System.out.println("over");
    }
   
    public static void method2() {//遇到第一个错误就跳出到catch,停止执行。
        try {
            int a = 10;
            int b = 0;
            System.out.println(a / b);// ArithmeticException
            int[] arr = { 1, 2, 3 };
            System.out.println(arr[3]);// ArrayIndexOutOfBoundsException
            System.out.println("over");
            
        }catch (ArithmeticException ae) {
            System.out.println("除数不能为0");
        }catch (ArrayIndexOutOfBoundsException ae) {
            System.out.println("数组越界异常");
        }
    }
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2