异常体系

java的异常体系

java的所有异常都是来自于一个共同的父类: Throwable类。

此类有两个子类,一是Error类,一是Exeption类,常见异常一般来自于Exception类

Exception类里比较重要的一个类为RuntimeException类

 

各项举例:

1.Error举例:

package com.study;

public class ThrowDemo {
    public static void main(String[] args) {
        //1.Error
        int[] arr = new int[1024*1024*1024];
    }
}

2.Exception 编译期异常

package com.study;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThrowDemo {
    public static void main(String[] args) {
//        //1.Error
//        int[] arr = new int[1024*1024*1024];

        //2.Exception
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
        Date date = simpleDateFormat.parse("2021-02-02");


    }
}

常有两种解决办法,一是抛出异常,不过会阻断程序运行,一是try catch,程序仍会运行

3.RuntimeException  运行时异常,编译时不会有提示

package com.study;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThrowDemo {
    public static void main(String[] args)  {
//        //1.Error
//        int[] arr = new int[1024*1024*1024];

        //2.Exception
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
//        Date date = null;
//        try {
//            date = simpleDateFormat.parse("2021-0202");
//        } catch (ParseException e) {
////            e.printStackTrace();
////            System.out.println(e);
//            System.out.println("aaa");
//        }
//        System.out.println(date);
//        System.out.println("后续代码");
//
        //3.RuntimeException
        int[] ints = new int[3];
        System.out.println(ints[3]);

    }
}

 

posted on 2021-02-02 12:11  沐楚  阅读(88)  评论(0)    收藏  举报

导航