前言
一、基本数据异常处理
public class Demo {
public static void main(String[] args) {
int a = wrong1();
System.out.println(a);
}
public static int wrong1() {
int a = 10;
try{
return a;
}catch(Exception e){
return 0;
}finally {
a = 20;
}
}
}
二、引用数据类型异常处理
public class Demo2 {
public static void main(String[] args) {
Person p = wrong2();
System.out.println(p.age);
}
public static Person wrong2() {
Person p = new Person();
try{
p.age = 18;
return p;
}catch(Exception e){
return null;
}finally {
p.age = 28;
}
}
static class Person {
int age;
}
}
总结
<font color=#999AAA
从根本来讲,基本数据类型存储在内存的栈当中,在执行try语句返回a的时候,系统会备份a的值为10,也就是说不管finall中的a的值如何改变,返回到方法中的a的值始终为10,不会改变。
而引用数据类型就不同了。因为引用数据类型新建了一个对象进行存储,也就是说new新建的对象值为18且存储在堆中,而栈中存储了age在内存的地址,修改了age的值为28以后,其地址不会改变,也就是说返回值根据地址最终会返回一个finall修改后的值28。
这就是基本数据类型和引用数据类型在异常处理的具体不同之处。