Java学习03 - 异常

1 - 异常

1.1 - 基本概念

​ 异常,指不正常,在Java中异常处理能让程序在异常发生的情况时,按照事先设定好的处理方式去有针对性的做处理。

java.lang.Throwable类是Java中所有错误和异常的超类,已知直接子类有:Error类和Exception类、

1.2 - 异常的主要分类

名称说明
RuntimeException运行时异常类,也叫作非检测性异常
IOExceptionIO异常类,也叫作检测性异常
RuntimException类的主要子类
异常类型说明
ArithmeticException算数异常
ArrayIndexOutofBoundsException数组下标越界异常
NullPointerException空指针异常
ClassCastException类型转换异常
NumberFormatException数组格式异常
运行时异常的处理方式

​ 绝大多数的运行时异常/非检测性异常都可以通过if()条件判断的形式避免发生

import java.io.IOException;

/**
 * @author ly_smith
 * @Description #TODO 运行时异常的主要分类
 */
public class Demo06 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        if(b != 0){
            System.out.println(a/b);//算数异常ArithmeticException
        }

        int[] arr = new int[5];
        int post = 5;
        if(post >= 0 && post < 5){
            System.out.println(arr[post]);//java.lang.ArrayIndexOutOfBoundsException
        }

        String s1 = null;
        if (s1 != null){
            System.out.println(s1.length());//java.lang.NullPointerException
        }

        Exception e = new Exception();
        if(e instanceof IOException){
            IOException io = (IOException) e;//java.lang.ClassCastException
        }

        String s2 = "123abc";
        if(s2.matches("\\d+")){
            System.out.println(Integer.parseInt(s2));//NumberFormatException
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值