概述
- java把所有非正常的情况分为两类,异常(Exception)和错误(Error),他们都继承自Throwable类

- Error错误,一般指jvm相关问题,系统崩溃,jvm错误等,不建议捕获Error,也无需throws Error及其子类,比如OutOfMemoryError,StackOverflowError
public void stackLeak(){
length++;
stackLeak();
}
public static void main(String[] args) {
StackOverTest stackOverTest = new StackOverTest();
try {
stackOverTest.stackLeak();
}catch (Throwable e){
System.out.println("length : "+ stackOverTest.length);
e.printStackTrace();
}
}
out:
length : 18894
@Test
public void test(){
ArrayList list = new ArrayList();
try {
while (true){
list.add(new Object());
}
}catch (OutOfMemoryError e){
e.printStackTrace();
}
}

- Exception异常,Exception类以及他的子类,代表程序运行时发送的各种不期望发生的事件。可以被Java异常处理机制使用,是异常处理的核心
Checked异常体系
- unchecked——所有的RuntimeException 及其子类 统称 Runtime异常,例如ArrayIndexOutOfBoundsException,NullPointerException,这样的异常,也可以不处理。对于这些异常,我们应该修正代码,而不是去通过异常处理器处理
- checked——不是runtime异常的则被称为Checked异常,例如SQLException , IOException,ClassNotFoundException,它要求开发者必须来处理这些异常,要么throw,要么try—catch
- checked异常提现了java的设计 – 没有完善错误处理的代码根本不会被执行。
finally和return的坑
- finally中的return 会覆盖 try 或者catch中的返回值
- 不要在finally中抛出异常
- finally用来释放资源最巴适
public int getNum(int num){
try{
int result = 10/num;
return 1;
}catch (Exception e){
System.out.println(e.getMessage());
return 2;
}finally {
return 3;
}
}
public int getNum2(int num){
try{
int result = 10/num;
return 1;
}catch (Exception e){
System.out.println(e.getMessage());
return 2;
}finally {
}
}
public int getNum3(int num){
try{
int result = 10/num;
return 1;
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
}
return 0;
}