Java-异常处理-try-catch

package Exception;

//异常梳理方式:try..catch..finally
//try{被检测的代码,即可能出现异常的代码}catch(异常类名  变量){异常梳理方式}finally{必须要执行的代码}
//catch 之间  如果是平级关系  没有顺序关系;如果是上下级关系异常(高级的写后面) 多态的运用
public class ExceptionDemo1 {
    public static void main(String[] args) {
        int[] arry = { 1 };
        try
        {
            fun(arry);
        } catch (NullPointerException e)// 实际上是e= new NullPointerException
        {
            System.out.println(e);
        } catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e);
        }finally {
            System.out.println("除非上面写了exit,无论啥异常,这里都会执行");
        }
    }

    public static void fun(int[] arr) throws NullPointerException, ArrayIndexOutOfBoundsException {
        // 对数组判空
        if (arr == null)
        {
            throw new NullPointerException("数组为空");
        }
        if (arr.length < 3)
        {
            throw new ArrayIndexOutOfBoundsException("数组越界");
        }
        int i = arr[3] + 1;
        System.out.println(i);
    }
}

原文地址:https://www.cnblogs.com/BruceKing/p/13522711.html