217 编译时异常和运行时异常的区别

217 编译时异常和运行时异常的区别

Java中的异常分为两大类:编译时异常(受检异常),运行时异常(非受检异常)。

> 编译 == 受检

Java中的异常

编译时异常(受检异常)

Compile time exception

Tested abnormality

必须显示处理,否则程序报错,无法通过编译

运行时异常(非受检异常)

Runtime exception

Non inspected abnormality

无需显示处理,也可以和编译时异常一样处理

-

ParseException继承自ParseException类,说明它是编译时异常

【代码的书写思路】

1.main方法写屏开始、结束字样,中间调用method方法

2.创建method方法,一个数组,输出索引越界的数组元素

2.创建method2方法,给出日期字符串,创建SimpleDateFormat对象并调用parse方法+自动装箱,把日期字符串转为Date类,然后输出日期数据

【报错了】

catch部分用了e. printStackTrace()控制台输出结果包括2行红字。

不确定这2行红字是代码写错了,还是e. printStackTrace()运行完就是这样。

回看e215的try…catch方法,讲师运行e. printStackTrace()后控制台也有2行红字。

所以代码没错,就是这样的。

--------------------------------------------------------------

(module)myException

(package)it01e217

class)ExceptionDemo

--------------------------------------------------------------

package it01e217;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class ExceptionDemo {

    public static void main(String[] args) {

        method();

        method2();

    }

    //编译时异常,例如parse异常

    public static void method2(){

        try{

            String s = "2021-09-23";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Date d = sdf.parse(s);

            System.out.println("d:\n"+d);

            //查帮助文档可知,ParseException继承自Exception类,说明它是编译时异常

        }catch(ParseException e){

            e.printStackTrace();

        }

    }

    //运行时异常

    public static void method(){

//        try{

//            int[] arr = {1,2,3};

//            System.out.println("217/arr[3]:\n"+arr[3]);

//        }catch(ArrayIndexOutOfBoundsException e){

//            e.printStackTrace();

//        }

//        上面已作废的代码,为什么写了try...catch还是一直报错说索引越界

        try{

            int[] arr = {1,2,3};

            System.out.println("217/arr[3]:\n"+arr[3]);

        }catch(ArrayIndexOutOfBoundsException e){

            e.printStackTrace();

        }

    }

}

Guess you like

Origin blog.csdn.net/m0_63673788/article/details/121508238