异常体系的执行顺序
https://blog.csdn.net/qq_43508801/article/details/96514788
总的来说分为两种情况:
1.基本数据类型:finally中有return,那么try和catch语句中的return会失效,返回finally中的return的值;若finally中无return语句,那么try和catch会暂存他们的值,再执行finally,最后返回暂存值
2.引用类型,若finally中含有return仍然会使try和catch中的return语句失效;若无return语句,如果finally中将变量修改,那么返回finally中修改的值;若finally新new了一个对象,但还用的原来的变量名,则不影响try,catch的暂存值
public class ExceptionTest { private int age; public static void main(String[] args) { //System.out.println(test2().age); System.out.println(test()); } // public static ExceptionTest test2() { // ExceptionTest exceptionTest = new ExceptionTest(); // try { // exceptionTest.age = 1; // return exceptionTest; // }catch (Exception e) { // exceptionTest.age = 2; // return exceptionTest; // }finally { // exceptionTest = new ExceptionTest(); // exceptionTest.age = 3; // return exceptionTest; // } // } // public static int test1() { // int i = 0; // try { // i = 1; // return i; // }catch (Exception e) { // i = 2; // return i; // }finally { // i = 3; // } // } // public static int test() { int i = 0; try { i = 1; return i; }catch (Exception e) { i = 2; return i; }finally { i = 3; return i; } } }

浙公网安备 33010602011771号