异常与错误

扫码查看

Throwable:
一、错误Error:一旦发生,不可处理,只能由程序员修改代码
二、异常:Exception
1.非RuntimeException:编译期异常,可以处理
2.RuntimeException运行期异常:不可处理,只能由程序员修改代码

package com.oracle.demo01;

public class Demo03 {
    //异常的处理方式
    //catsh 补获的时候,注意子父类关系,子类在上面,父类在下面
    public static void main(String[] args)  {
        //int [] arr={1};
        int [] arr={};
        int a=0;//可执行处理异常
        try {
            //try之内放可能会产生异常的代码,其内代码若发生异常,不会再继续执行   //对可疑代码进行检测
            a=get(arr);
            System.out.println(a);
        } catch (NullPointerException e) {
            //一旦发生异常,执行的代码:throw什么异常,就写什么异常 + 变量名 //对异常代码进行处理
            e.printStackTrace();
        }catch (ArrayIndexOutOfBoundsException ex) {
            ex.printStackTrace();
        }catch (Exception exe) {//放到最后,以备不患

        }finally {//不管发不发生,都执行的代码,可写可不写
            System.out.println("一定回执行的代码!");
        }
        System.out.println("我是无关代码,继续执行!");
    }

    public static int get(int[] arr) throws ArrayIndexOutOfBoundsException,NullPointerException,Exception{
        if(arr.length==0){
            throw new ArrayIndexOutOfBoundsException();//抛出的是个对象,需要new
        }
        if (arr==null) {
            throw new NullPointerException();
        }
        if (arr.length<2) {
            throw new Exception();
        }
        int i=arr[0];
        return i;
    }
}

.

12-26 10:10
查看更多