java 异常(Exception)

java语言中,将程序执行中发生的不正常情况称为"异常"
执行过程中所发生的异常事件可分为两类:

  • Error(错误):Java虚拟机无法解决的严重问题.如:JVM系统内部错误,资源耗尽等情况.如此: StackOverflowError[栈溢出]和OOM(out of memory),Error是严重错误,程序会本崩溃
  • Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理.例如空指针访问,视图读取不存在的文件,网络连接中断等等,Exception分为两大类:运行时异常编译时异常.
    在这里插入图片描述
  • 异常分为两大类: 运行时异常和编译时异常
  • 运行时异常,编译器不要求强制处理的异常.一般是指编程时的逻辑错误,是程序员应该避免其出现的异常.java.lang.RuntimeException类以及它的子类都是运行时异常
  • 运行时异常,可以不作处理,因为这类异常很普遍,若处理可能会对程序的可读性和运行效率产生影响
  • 编译时异常,是编译器要求必须处置的异常

常见运行时异常

NullPointerException

当应用程序试图在需要对象的地方使用null时,抛出异常

public class NullPointerExceptionDemo {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.length());
    }
}


Exception in thread "main" java.lang.NullPointerException
	at com.ll.exceptiondemo.NullPointerExceptionDemo.main(NullPointerExceptionDemo.java:10)

ArithmeticException 算数异常

ArrayIndexOutOfBoundException 数组下标越界异常

用非法索引访问数组时抛出异常,如果索引为负或大于等于数组大小,则该索引为非法索引

public class ArrayIndexOutOfBoundsExceptionDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        System.out.println(arr[5]);
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
	at com.ll.enum_.ArrayIndexOutOfBoundsExceptionDemo.main(ArrayIndexOutOfBoundsExceptionDemo.java:10)

ClassCastException 类型转换异常

当试图将对象强制转换为不是实例的子类时,抛出该异常

public class ClassCastExceptionDemo {
    public static void main(String[] args) {
        // 向上转型
        A a = new B();

        // 向下转型
        B b = (B)a;

        // ClassCastException
        C c = (C)a;
    }
}

class A { }

class B extends A{}

class C extends A{}

NumberFormatException 数字格式异常

当程序试图将字符串转为一种数值类型,但该字符串不能转为适当格式时,则抛出改改异常

public class NumberFormatExceptionDemo {
    public static void main(String[] args) {
        String name = "ll";
        int i = Integer.parseInt(name);
        System.out.println(i);
    }
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "ll"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at com.ll.exceptiondemo.NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:10)

编译异常

编译异常指在编译期间,就必须处理的异常,否则代码不能通过编译

SQLException

FileNotFoundException

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值