public class Test { public static void main(String[] args) { System.out.println("=============test1=================="); System.out.println(test1()); System.out.println("==============================="); System.out.println("=============test1_1=================="); System.out.println(test1_1()); System.out.println("==============================="); System.out.println("\n============test2==================="); System.out.println(test2()); System.out.println("==============================="); System.out.println("\n============test2_1==================="); System.out.println(test2_1()); System.out.println("==============================="); System.out.println("\n============test3==================="); System.out.println(test3()); System.out.println("==============================="); System.out.println("\n============test3_1==================="); System.out.println(test3_1()); System.out.println("==============================="); } public static String test0() { String a; int b; try{ b = 8/0; }catch(Exception e){ return null; } a = String.valueOf(b); return a+b; } public static String test0_1() { String a; int b; try{ b = 8/0; a = String.valueOf(b); return a+b; }catch(Exception e){ return null; } //return a+b; } public static String test0_2() { String a; int b=0; try{ b = 8/0; }catch(Exception e){ } a = String.valueOf(b); return a; } public static String test1() { String a = "in try"; int n = -1; try{ return a+n; //先执行这个,再执行finally } catch ( Exception e ) { } finally { //对String和int的更改均无效 a = "in finally"; n = 123; System.out.println("do finally"); } return a; //不会执行 } //总结出一点:return语句并不是函数的最终出口,如果有finally语句,这在return之后还会执行finally public static String test1_1() { String a = "in try"; try{ return a; } catch ( Exception e ) { } finally { //从eclpise报警告可看出,finally里面不建议有return语句 a = "in finally"; System.out.println("do finally"); return a; //注释掉这句,eclipse将不再警告 } } public static int test2() { int a = 1; try{ return a; } catch ( Exception e ) { } finally { a = 2; System.out.println("do finally"); } return a; } //很显然,finally里面更改无效,返回的是a=1 public static int test2_1() { int a = 1; try{ return a; } catch ( Exception e ) { } finally { a = 2; System.out.println("do finally"); return a; } } //很显然,a取finally里面的值,a=2 //Helper类,将整数转换成字符串 static class Helper { int a; public String toString() { return String.valueOf(a); } } public static Helper test3() { Helper h = new Helper(); h.a = 1; try{ return h; } catch ( Exception e ) { } finally { h.a = 2; //对h.a的更改起作用!! //因为在try里面返回的是一个句柄,它指向的对象的内容 是可以改变的 System.out.println("do finally"); } return h; //这个不会被执行 } public static Helper test3_1() { Helper h = new Helper(); h.a = 1; try{ return h; } catch ( Exception e ) { } finally { h.a = 2; //返回a=2,这个不用说了 System.out.println("do finally"); return h; } } /** * 总结: * return语句,finally里面不建议放return语句,根据需要,可以放在try和catch里面 * */ }
|