Java——常见异常

一、异常介绍

基本概念
程序执行中发生的不正常情况称为“异常”(开发中的语法错误和逻辑错误不是异常)

两大类

  1. Error :Java虚拟机无法解决的错误 像栈溢出
  2. Exception :其他因为编程错误或偶然的外在因素导致的一般性问题,可以使用代码进行处理;分为两大类:运行异常和编译异常

二、异常体系图

在这里插入图片描述


三、五大运行异常

一、NullPointerException空指针异常

package com.ylxstudy.exception_;

/**
 * @author 杨乐昕
 * @version 1.0
 * 空指针异常
 */
public class NullPointerException_ {
    public static void main(String[] args) {
//        String name = "小黄";
        String name = null;
        System.out.println(name.length());
        /*
        * 空指针异常
        * Exception in thread "main" java.lang.NullPointerException
	at com.ylxstudy.exception_.NullPointerException_.main(NullPointerException_.java:11)
        * */
    }
}

二、ArithmeticException算数运算异常

package com.ylxstudy.exception_;

/**
 * @author 杨乐昕
 * @version 1.0
 * 数学运算异常
 */
public class ArithmeticException_ {
    public static void main(String[] args) {
        int n1 = 22;
        int n2 = 0;
        int number = n1 / n2;
        System.out.println(number);
        //算术异常
        //Exception in thread "main" java.lang.ArithmeticException: / by zero
    }
}

三、ArrayIndexOutOfBoundsException数组下标越界异常

package com.ylxstudy.exception_;

/**
 * @author 杨乐昕
 * @version 1.0
 * 数组下标越界异常
 */
public class ArrayIndexOutOfBoundsException_ {
    public static void main(String[] args) {
        int[] arr={1,2,4 };
        for (int i= 0;i<=arr.length;i++){
            System.out.println(arr[i]);
        }
        //数组下标越界异常
        //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

    }
}

四、ClassCastException类型转换异常

package com.ylxstudy.exception_;

/**
 * @author 杨乐昕
 * @version 1.0
 * 类型转换异常
 */
public class ClassCastException_ {
    public static void main(String[] args) {
        A b = new B();//向上转型 b 指向 对象B
        B b1 = (B)b;//将引用对象b 向下转型 为B 编译类型
        C b2 = (C) b;//b事先没有先指向C对象 不能进行向下转型
        //Exception in thread "main" java.lang.ClassCastException:
        // com.ylxstudy.exception_.B cannot be cast to
        // com.ylxstudy.exception_.C
    }
}
class A{}
class B extends A{}
class C extends A{}

五、NumberFormatException数字格式不正确异常

package com.ylxstudy.exception_;

/**
 * @author 杨乐昕
 * @version 1.0
 * 数字格式不正确异常
 */
public class NumberFormatException_ {
    public static void main(String[] args) {
        String name = "小黄";
        int num = Integer.parseInt(name);
        //小黄字符串不能转换为数字,抛出异常
        //Exception in thread "main" java.lang.NumberFormatException:
        // For input string: "小黄"
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云来喜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值