The {@code Throwable} class is the superclass of all errors and
exceptions in the Java language.:这句话是说Throwable是java语言中所有异常错误的超类,注意看这句话all errors and exceptions
相信很多人都很经常在异常错误信息中看到exceptions
,error这个词本身就是错误的意思,所以这个all errors and exceptions
是不是指代java异常的两种错误,事实上是的,java中的错误大体上分为两种,一种是exception
,一种是error
。
1
、exception是什么样子的错误?
(1)检查时异常
:在代码中碰到报异常让人往外抛出,或try…catch…的,便是检查时异常
(2)非检查时异常
:例如在代码运行时,报了数组下标越界异常、空指针异常、算数逻辑异常等
a.下标越界
public static void main(String[] args) {
String[] str = {};
System.out.println(str[1]);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
b.算数逻辑异常
public static void main(String[] args) {
int i= 0;
i = 1/0;
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
c.空指针异常
public static void main(String[] args) {
System.out.println(contrast(null, "12"));
}
public static int contrast(String str1,String str2){
return str1.length()-str2.length();
}
Exception in thread "main" java.lang.NullPointerException
2
、error是什么异常?
是在jvm上的异常,
(1)如OutOfMemoryError
内存空间异常,比如一直引用新的对象,但是不释放,内存溢出
(2)如StackOverflowError
:堆栈溢出异常
总结
(1)异常分为exception和error
(2)exception分为检查时异常(try…catch…)和非检查时异常(空指针异常、算数逻辑异常等)
(3)error是jvm上的异常(堆栈溢出异常,内存溢出异常)