异常处理 ?处理(try-catch) :甩锅(throws)_ java异常(Exception)处理(2)

96 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第30天,点击查看活动详情

异常体系图

在这里插入图片描述只是举例了几种常见的异常! 大家可以下去自行查看 异常体系图十分方便体现了继承和实现的关系! 虚线是实现接口,实线是继承父类! IEDA查看类的关系图步骤: 1.找到一个类选中 2.鼠标右击 3.选择 在这里插入图片描述4.然后再选择该类,鼠标右击查看,选择你要展现父类或者子类! 在这里插入图片描述 异常体系图的小结 基本概念 java语言中,将程序执行中出现的不正常情况称为“异常”(开发中语法错误和逻辑错误不是异常)

运行时异常

常见的运行时异常包括

  1. NullPointerException 空指针异常
  2. ArithmeticException 数学运算异常
  3. ArrayIndexOutOfBoundsException 数组下标越界异常
  4. ClassCastException 类型转换异常
  5. NumberFormatException 数字格式不正确异常

常见运行时异常举例

  • NullPointerException 空指针异常
//空指针异常
public class NullPointerException_ {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length());//NullPointException
    }
}

在这里插入图片描述

-ArithmeticException 数学运算异常

//数学运算异常
public class ArithmeticException_ {
    public static void main(String[] args) {
        int m = 10;
        int n = 0;
            System.out.println(m/n);//分母不能为0 算数异常
    }
}

在这里插入图片描述

  • ArrayIndexOutOfBoundsException数组越界异常
//数组下标越界异常
public class ArrayIndexOutOfBoundsException_ {
    public static void main(String[] args) {
        int[] arr = new int[3];
        System.out.println(arr[4]); //arr下标[0,2]
    }
} 

在这里插入图片描述

  • ClassCastException类型转换异常
//类型转换异常
public class ClassCastException_ {
    public static void main(String[] args) {
        String string = "java";
        Object ob = string; //上转型对象
        Integer integer = (Integer)ob; //类型转换异常
    }
}

在这里插入图片描述

-NumberFormatException 数字格式不正确异常

//数字格式不正确异常
public class NumberFormatException_ {
    public static void main(String[] args) {
        int a = Integer.parseInt("1aba");//将字符串转换成整型
                                         //数字格式不正确异常
    }
}

在这里插入图片描述