Error表示系统级的错误和程序不必处理的异常,是恢复不是不可能但很困难的情况下的一种严重问题;比如内存溢出,不可能指望程序能处理这样的情况;
举例:
import java.util.ArrayList;
import java.util.List;
public class OutOfMemoryTest {
public static void main(String[] args){
List list=new ArrayList();
for(;;){
int[] tmp=new int[1000000];
list.add(tmp);
}
}
}
报错:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
public class StackOverflowTest {
public static void main(String[] args) {
method();
}
public static void method(){
for(;;)
method();
}
}
报错:Exception in thread "main" java.lang.StackOverflowError
Exception表示需要捕捉或者需要程序进行处理的异常,是一种设计或实现问题;也就是说,它表示如果程序运行正常,从不会发生的情况。
ArrayIndexOutOfBoundsException 数组下标越界异常,
public class StackOverflowTest {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
System.out.println(a[7]);
}
}
报错:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
ArithmaticException 算数异常 如除数为零
public class StackOverflowTest {
public static void main(String[] args) {
System.out.println(1/0);
}
}
报错:Exception in thread "main" java.lang.ArithmeticException: / by zero
NullPointerException 空指针异常
public class StackOverflowTest {
public static void main(String[] args) {
String s = null;
System.out.println(s.toLowerCase());
}
}
报错:Exception in thread "main" java.lang.NullPointerException
IllegalArgumentException 不合法参数异常
拓展:
2005年摩托罗拉的面试中曾经问过这么一个问题“If a process reports a stack overflow run-time error, what’s the most possible cause?”,给了四个选项
a. lack of memory;
b. write on an invalid memory space;
c. recursive function calling;
d. array index out of boundary.
Java程序在运行时也可能会遭遇StackOverflowError,这是一个无法恢复的错误,只能重新修改代码了,这个面试题的答案是c。
如果写了不能迅速收敛的递归,则很有可能引发栈溢出的错误。
提示:用递归编写程序时一定要牢记两点:
1. 递归公式;
2. 收敛条件(什么时候就不再继续递归)。