return在try块里作用范围

来源:互联网 发布:淘宝电脑版 编辑:程序博客网 时间:2024/05/29 09:43

以下程序输出结果是30


程序走try块里累加10,并没有返回值(跳过了try块里的return),而直接走finally块里累加10,而后返回结果


public class Demo{public static void main(String args[]){int num = 10;System.out.println(test(num));}public static int test(int b){try{b += 10;return b;}catch(RuntimeException e){}catch(Exception e2){}finally{b += 10;return b;}}}

注释掉finally里的return 程序直接报错

public class Demo{public static void main(String args[]){int num = 10;System.out.println(test(num));}public static int test(int b){try{b += 10;return b;}catch(RuntimeException e){}catch(Exception e2){}finally{b += 10;//return b;}}}

以下程序都没执行try里的return

public class Demo{public static void main(String args[]){int num = 10;System.out.println(test1(num));System.out.println(test2());System.out.println(test3().toString());}public static int test1(int b){try{b += 10;return b;}catch(RuntimeException e){}catch(Exception e2){}finally{b += 10;return b;}}public static String test2(){    String test = "111";    try {        test = "222";        return test;    } catch( Exception e) {    } finally {        test = "333";        return test;    }}public static StringBuffer test3(){    StringBuffer test = new StringBuffer();    try {        test.append("123");        return test;    } catch( Exception e) {    } finally {        test.append("456");        return test;    }}}


运行结果:

30 

333

123456






阅读全文
0 0
原创粉丝点击