万物皆是类,异常也是一种类,在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)
发现显示抛出的位置不同