Exception异常

异常:在程序执行过程中出现的非正常现象,最终导致JVM非正常停止。在Java等面向对象的编程语言中,异常本省就是一个类,产生异常就是创建异常对象,并且抛出异常对象。Java处理遗异常的方式是中断处理
需要注意的是异常值得并不是语法错误,语法错误根本无法编译通过,不会产生字节码文件,根本不能运行
异常的根类是Throwable,他有两个子类Error和Exception
Error:java.lang.Error
Exception:java.lang.Exception
Exception:编译期异常,进行编译Java程序过程中出现的问题
RuntimeException:运行期异常,Java程序运行过程出现的问题

        int[] arr = {1,2,3};
        try {// 有可能出现异常的代码
            System.out.println(arr[3]);
        }
        catch (Exception e) {// 处理异常
            System.out.println(e);// java.lang.ArrayIndexOutOfBoundsException: 3
            System.out.println("出现异常");
        }
        System.out.println("还可以继续执行");

异常抛出的过程:

throw关键字:在指定的方法中,抛出指定的异常
使用格式:

throw new xxxException

注意:
1、throw必须写在方法的内部
2、throw关键字后面new的对象必须是Exception或者Exception的子类的对象
3、throw关键字抛出的指定的异常对象,我们就必须处理这个异常
throw关键字后面创建的是RuntimeException或者是RuntimeException子类的对象我们可以不处理,交给JVM处理(打印异常对象,中断程序)
throw关键字后面创建的是编译异常(写代码的的时候报错),就必须处理,要么throw要么try catch

package cn.zhuobo.day10.aboutException;

public class Demo01Throw {
    public static void main(String[] args) {
        int[] arr = null;
        int[] arr2 = new int[3];
        System.out.println(getElement(arr2, 9));

        System.out.println("=========================");
        System.out.println(getElement(arr,2));
    }

    public static int getElement(int[] arr, int index) {
        if(arr == null) {
            throw new NullPointerException("数组为空");
        }
        if(index < 0 || index >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("索引越界");
        }
        return arr[index];
    }
}

Objects的一个静态方法可以进行非空判断:
public static T requireNonNull(T obj)

public static void method(Object obj) {
    String message = "传递的对象为空";
    Objects.requireNonNull(obj, message);
}

当调用这个方法来判断的时候,如果参数obj是空,那么就打印空指针异常,以及message

原文地址:https://www.cnblogs.com/zhuobo/p/10632710.html