Java学习笔记——Exception(异常)——认识异常

1. 定义

Exception(异常)
代表程序可能出现的问题
在这里插入图片描述

  • 运行时异常RuntimeException及其子类,指的编译阶段不会出现错误提醒,运行时出现的异常(如:数组索引越界异常)
  • 编译时异常:编译阶段出现的错误提醒(如:日期解析异常)
  • Error:系统级别的异常,如果系统出现了问题,会通过Error对象呈现

2. 异常代码示例

2.1 运行时异常

// 运行时异常
public class ExceptionDemo1 {
    public static void main(String[] args) {
        show();
    }
    public static void show(){
        int[] arr = {1,2,3};
        System.out.println(arr[3]);
    }
}

运行结果
在这里插入图片描述
可以看到异常报错,判断是否为运行时时异常,按住Ctrl和右击红框内ArrayIndexOutOfBoundsException查看其是否继承RuntimeException类
在这里插入图片描述
ArrayIndexOutOfBoundsException继承IndexOutOfBoundsException类,而IndexOutOfBoundsException类继承RuntimeException,因此该异常是一个运行时异常
在这里插入图片描述

其它运行时异常

10/0的异常
// 运行时异常——10/0
public class ExceptionDemo1 {
    public static void main(String[] args) {
        show();
    }
    public static void show(){
        System.out.println(10/0);
    }
}

运行结果
在这里插入图片描述

空指针异常
// 运行时异常——空指针异常
public class ExceptionDemo1 {
    public static void main(String[] args) {
        show();
    }
    //运行时异常
    public static void show(){
        String str=null;
        System.out.println("字符串为:"+str);
        System.out.println("字符串长度为:"+str.length());
    }
}

运行结果
在这里插入图片描述

2.2 编译时异常

// 编译时异常-时间解析
public class ExceptionDemo1 {
    public static void main(String[] args) {
        show();
    }
    //运行时异常
    public static void show(){
        String str=null;
        System.out.println("字符串为:"+str);
        System.out.println("字符串长度为:"+str.length());
    }
}

在这里插入图片描述
该异常的解释是:
java.text.ParseException 是 Java 中的一个异常类,用于表示解析文本时发生的错误。当你使用 java.text 包中的类(如 SimpleDateFormat)将字符串转换为日期或其他格式化对象时,如果输入的字符串不符合预期的格式,就会抛出 ParseException

3. 异常的基本处理

抛出异常(throws)和捕获异常(try…catch)

3.1 抛出异常

在方法上使用throws关键字,可以将方法内部出现的异常抛出去给调用者处理

方法 throws 异常1, 异常2, 异常3 ...{
         ...
}

3.2 捕获异常(try …catch)

直接捕获程序出现的异常

try{
    //监视可能出现的异常的代码
  }catch(异常类型1 变量){
     //处理异常
  }catch(异常类型2 变量){
     //处理异常
  }

3.3 异常处理示例

这里选用日期解析异常

3.3.1 抛出异常

可以将选中异常出现的地方,按住Alt,然后按回车,然后再按一次回车
在这里插入图片描述
然后选第一个,会在show()函数后面抛出异常,抛出给调用者
在这里插入图片描述
接着可以将main函数继续抛出异常
在这里插入图片描述
运行后的结果
在这里插入图片描述

3.3.2 捕获异常

在main函数中来捕获show函数运行的异常,并打印异常
在代码中将解析的日期格式改变一下
在这里插入图片描述

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值