Java 异常体系(简述)

万物皆是类,异常也是一种类,在Java中,异常体系中的最终父类为Throwable

Throwable有两个子类:

  • Error类:一般是严重问题,主要在内存上的问题,由Java虚拟机直接抛出
  • Exception类:一般性的问题,用throw语句抛出,也可由Java虚拟机抛出

当然我们也可以->自定义异常类

Error

由Java虚拟机抛出

 举个例子:

import java.util.ArrayList;

public class Test {

	public static void main(String[] args) {
		ArrayList<Demo> list1=new ArrayList<>();
		while(true) {
			list1.add(new Demo());
		}
	}
}
class Demo{
	
	private Byte[] b = new Byte[1024*1024*1024];//空间大小为1GB
	public Demo() {
		
	}
}

 异常:堆内存溢出

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at Demo.<init>(Test.java:14)
	at Test.main(Test.java:8)

 

Exception

由Java虚拟机直接抛出(懒人) 或者throw抛出

 举个例子:

懒人写法:

public class Test {

    public static void main(String[] args) {
        int[] s=new int[10];
        int index=10;
        s[index]=1;//第7行抛出
    }
}

 异常:超出角标,现在是由Java虚拟机抛出

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
	at Test.main(Test.java:7)

手动写throw:

public class Test {

    public static void main(String[] args) {
        int[] s=new int[10];
        int index=10;
        if(index<0 || index>s.length-1) {
            throw new ArrayIndexOutOfBoundsException();//第8行抛出
        }
        s[index]=1;
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
	at Test.main(Test.java:8)

发现显示抛出的位置不同

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值