多异常的捕获方式以及自定义异常类

隐身守侯 提交于 2020-01-28 17:05:18

多异常的写法以及自定义异常类

1.多异常的三种捕获方式及注意事项:

public static void main(String[] args) {
        //1
        try{
            int[] arr = {1,2,3};
            System.out.println(arr[3]);
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }
        try{
            List<Integer> integers = List.of(1, 2, 3);
            System.out.println(integers.get(3));
        }catch (IndexOutOfBoundsException e){
            e.printStackTrace();
        }
        System.out.println("+++++++++++++++");
        //2.当catch中捕获的异常变量有子父类关系时,子类先写在上面,否则报错
        try{
            int[] arr = {1,2,3};
            System.out.println(arr[3]);
            List<Integer> integers = List.of(1, 2, 3);
            System.out.println(integers.get(3));
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }catch(IndexOutOfBoundsException e){
            e.printStackTrace();
        }
        System.out.println("++++++++++++");
        //3.
        try {
            int[] arr = {1,2,3};
            System.out.println(arr[3]);
            List<Integer> integers = List.of(1, 2, 3);
            System.out.println(integers.get(3));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

2.自定义异常类:
java提供的异常类,不能满足我们使用,就需要我们自定义异常类
注意:
1.自定义异常类一般都以Exception结尾,说明该类是一个异常类
2.自定义异常类,必须继承Exception或RuntimeException
继承Exception:那么此异常就是编译期异常,如果方法内部抛出了编译期异常,就必须处理
继承RuntimeException:运行期异常,此异常可处理,可交给JVM处理。
3.自定义异常类,需添加一个带异常信息的方法,可以自定义错误提示。

public class RegisterException extends Exception{
    public RegisterException() {
        //调用父类
        super();
    }
    //添加一个带异常信息的方法
    //查看源码发现,所有的异常类都有一个带异常信息的构造方法
    //方法内部会调用父类带异常信息的方法,让父类来处理这个异常
    public RegisterException(String message) {
        super(message);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!