异常
Throwable类
Error类
两种常见的致命错误
import java.util.ArrayList;
public class Demo1 {
public static void main(String[] args) {
ArrayList<String> A1 = new ArrayList<String>();
while(true) {
A1.add("abc"); //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space ,内存溢出错误。
}
}
}
public class Demo2 {
public static void main(String[] args) {
show(); //Exception in thread "main" java.lang.StackOverflowError , 栈内存错误,这种存在于code的反复调用。
}
public static void show() {
show();
}
}
Exception
两种类型:
1. 编译器异常:比如需要import的或者需要catch的语法。无法生成.class文件
2. 运行时异常(RuntimeException):编译不报错,但是运行报错,比如空指针异常。
Java中如何处理异常:
原则1:一出异常,线程立刻结束,这里需要注意。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 3 at Demo3.main(Demo3.java:5)
原则2:提示错误在哪一行。
try catch可以抓住异常后,继续往下执行。
try {
可能异常}
catch(异常类 异常变量名){
做点什么}
public class Demo3 {
public static void main(String[] args) {
int[] a= {1,2,3};
try {
String nullString = null;
System.out.println(nullString.equals(a));
System.out.println(a[100]);
}
catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号