关于Java中的try-catch-finally语句和return

上一篇 / 下一篇  2012-08-21 09:15:25 / 个人分类:Java

AN.a3t|D2M0  第一:return语句并不是函数的最终出口,如果有finally语句,这在return之后还会执行finally(return的值会暂存在栈里面,等待finally执行后再返回)

z y hP7dS Oz051Testing软件测试网vt%lB p pK K I

  第二:finally里面不建议放return语句,根据需要,return语句可以放在try和catch里面和函数的最后。可行的做法有四:51Testing软件测试网3\/vE ZZ9[w i

1S qG;f@q[ [ ~@%Y(k0  1、return语句只在函数最后出现一次。

c$Ois"wy i.J051Testing软件测试网T;Pd%NG

  2、return语句仅在try和catch里面都出现。51Testing软件测试网7lrv1Q4xp

P1Uc@ W'o5m0  3、return语句仅在try和函数的最后都出现。51Testing软件测试网W4u;Q"Yn{(j} B.\

7O(XD2m2S s0  4、return语句仅在catch和函数的最后都出现。51Testing软件测试网O%y5b{(~}!iK

51Testing软件测试网 P8T;?/wI qn P$?R

  注意,除此之外的其他做法都是不可行的,编译器会报错。51Testing软件测试网 y#Dh/F%`#x1Zj

Ql| y2gf)q0  (1)如果程序运行到try成功时可以返回结果,则采用方法2。(见下面的例子test0_1,在那个例子中,方法2和4都是可行的,但是推荐方法2?)

[](c,Y"D0b*[/N-^f0

U9f@"Ux o0  (2)如果程序运行到catch时(即中途出错时)无需再继续执行后面的代码了,则采取方法4;(见下面例子中的test0,在那个特殊的例子中,只能采取方法4)

-oo!t3C } M051Testing软件测试网/k*V6~QRq2\)|l[

  (3)如果程序运行到try或catch时还需要继续执行后面的代码,则采取方法1(见下面的例子test0_2,该例子只能采用方法1)。

X[{&Gm0

\.z j*sEESooF7dq0  下面是测试代码:

F*f9Mih/U0

_5w0o;J'M i kZ0public classTest{51Testing软件测试网3V2Ow2jF"}

51Testing软件测试网 Vv&Cb*l1Keh

    public static void main(String[] args) {51Testing软件测试网l8^hJy
        System.out.println("=============test1==================");
n"n$yi&d&f6@~;[0        System.out.println(test1());
;Kd#U#L8b"QZ*O(GQ"V0        System.out.println("===============================");
51Testing软件测试网;vP-VKN2W

Jr*B'l m.a:q0        System.out.println("=============test1_1==================");51Testing软件测试网0p0K9~Vclv5B9`}
        System.out.println(test1_1());51Testing软件测试网l;q*hw5Ft:p[ d
        System.out.println("===============================");
51Testing软件测试网D%PywI/EfH

A2H*Tl's_QD0        System.out.println("\n============test2===================");51Testing软件测试网;jH5R7y7F5q \J
        System.out.println(test2());
%^X[j2V,B0        System.out.println("===============================");

l*A#WHglv2g6H%I051Testing软件测试网oy H eH i;D%J@

        System.out.println("\n============test2_1===================");51Testing软件测试网 K tM n;v'ul
        System.out.println(test2_1());
8Q\F2\*z0        System.out.println("===============================");
51Testing软件测试网:jn7_Bi}B

51Testing软件测试网3sS0D4LO

        System.out.println("\n============test3===================");
G-p,Ve P4s|@\#L0        System.out.println(test3());51Testing软件测试网1?g JP U/T3t
        System.out.println("===============================");
51Testing软件测试网s:j2~yvT

51Testing软件测试网gl0x1[u I/_

        System.out.println("\n============test3_1===================");
`gOc%D&r-c0        System.out.println(test3_1());
$Z L{ Q g!g"L0        System.out.println("===============================");51Testing软件测试网$Cu2vx*R P
    }
51Testing软件测试网 CE;RP`qV*{

51Testing软件测试网*ui1G?ueiqGn

    public static String test0() {
)E5XP i$~[Lb/z+T0     String a;
5b,|h+q/t'p;okb2m0     int b;
^)?\"?x f-W5k+P0     try{
@sy q:[0      b = 8/0;51Testing软件测试网+z,S T2ZcmI
     }catch(Exception e){51Testing软件测试网 Q"wB.Z$^.i&h
      return null;
E&] I7_ {#Bn{wT#s0     }
z+I$|&Ry0     a = String.valueOf(b);51Testing软件测试网\:e1~ T [D
     return a+b;
4|(Lz"v?Wm0    }51Testing软件测试网;^eBiK5u
 51Testing软件测试网|Fg@!Q#X:] {] @
    public static String test0_1() {51Testing软件测试网9r_$Wj1I IV
     String a;51Testing软件测试网([$OM8t`3A
     int b;
/\tTWH#kEq0     try{
g~ `hZ0      b = 8/0;
.X Z u+Z7G6i&l0      a = String.valueOf(b);
T([Z dy0         return a+b;
3x[H|Y7^.x)Fj9E7O[0     }catch(Exception e){
u,S^!X?0      return null;
o&Rg ?}0     }
H0c$Y)^"x'l7}0     //return a+b;
)S&[4`+V8w$s C0    }
3twd:M$E?$i?6F-X0   51Testing软件测试网` ?9H%] V/JN
    public static String test0_2() {
+W@vI$X*z#]#n0     String a;51Testing软件测试网 v4Q1B8[(LF
     int b=0;
_/] qD?+N}[0     try{
Uyk,gF1q0      b = 8/0;
O*O [4d C0     }catch(Exception e){
7Ng? y e$AChT0     }51Testing软件测试网/E)V3H$K{/K
     a = String.valueOf(b);51Testing软件测试网7Z4D^En)@ps%_Pb
     return a;
8b8DD6H|_0    }51Testing软件测试网^7T2e'k-v5c+Mb+r/V
   
S;guL!l4j0    public static String test1() {51Testing软件测试网 t.at8_ K;Wg"EV
        String a = "in try";51Testing软件测试网 \[Cd G{D.V!J9w
        int n = -1;51Testing软件测试网!Wr#o5p| L.b4S
        try{
(QL&J\'A0            return a+n; //先执行这个,再执行finally
/l0bV+{4WV'V1K0        } catch ( Exception e ) {

C2j&q7?4u.[3W_051Testing软件测试网Gl&W%IUl,jZ(J![

        } finally {51Testing软件测试网1[ rL2x!c
         //对String和int的更改均无效
(s6N g6`i?i0            a = "in finally";51Testing软件测试网.I.X/QB7pv v k
            n = 123;
F2p,m n e0            System.out.println("do finally");51Testing软件测试网a%o,W` MK#l
        }
#vF*R4n)WE2p-?4i4w0        return a; //不会执行51Testing软件测试网Z Iv'v_Z6K4RBL&b
    }  //总结出一点:return语句并不是函数的最终出口,如果有finally语句,这在return之后还会执行finally

qB vi-E e$g$jZB0

;M?.t%z)e h _,SU;JHQ0    public static String test1_1() {51Testing软件测试网FR'O2~4F|
        String a = "in try";

%G2\;P0n:Z D/^|051Testing软件测试网$TQwl&M*C ^

        try{51Testing软件测试网1^1D9Ls)@]o\uj
            return a;51Testing软件测试网,GyL.wp@
        } catch ( Exception e ) {

y&@h1^+{051Testing软件测试网1wt6|;OG

        } finally { //从eclpise报警告可看出,finally里面不建议有return语句51Testing软件测试网9e#P0M2E Iw4ifP
            a = "in finally";
2`omL8W;f6r!O ~0            System.out.println("do finally");
OZT:lFBb0            return a; //注释掉这句,eclipse将不再警告51Testing软件测试网.^n']J#P7\ lPZ
        }
7d7UQg"pHG6w` ]3y0    }

+P?%HOrm O)dc-F:d?0

@gb3I3`-Gg*M'J5B0    public static int test2() {
|AnD8t-y4Z4h0        int a = 1;
51Testing软件测试网 _#J/M l\Y-f#j

-`h m$t7zQ0        try{
t7X!\#wJ0            return a;51Testing软件测试网T Hw,KkK J
        } catch ( Exception e ) {
51Testing软件测试网/e]? x%q9a

51Testing软件测试网7|6^u}D

        } finally {
8m%`B/RI6~{@0            a = 2;51Testing软件测试网4v:EU9c:M5Sy
            System.out.println("do finally");
&o`ylI }FP1I)v0        }
51Testing软件测试网/Kg/k4h/e9Ze5b/l%X

^Az;e`+]k-t0        return a;
N2b R4Y ] qb0    } //很显然,finally里面更改无效,返回的是a=1

v1b;UqYh jR0

I0ok `:j&@^'ABt0    public static int test2_1() {51Testing软件测试网6G:xrW ?D$E6B
        int a = 1;
51Testing软件测试网"T7c7?us3['Q

51Testing软件测试网'LYg:?x

        try{
k9c UD9S0            return a;
0L4egNU2WQ:@0        } catch ( Exception e ) {

w8zZTT4c_0

}%G:l^w8]s T.`0        } finally {51Testing软件测试网^,H0ppS5PC
            a = 2;
_'yR+t&zDg0            System.out.println("do finally");
@S/\T4iG!r.[}0            return a;
G1H"D/_(eX5t#vuv.a0        }51Testing软件测试网'bu3qgI }
    } //很显然,a取finally里面的值,a=2

O p"tJ%~&P#w051Testing软件测试网K(v{ m&^'a!Z7I@

    //Helper类,将整数转换成字符串51Testing软件测试网:K*U8Fv,w,r SLv A
    static class Helper {51Testing软件测试网Z N(~)O+X I
        int a;

[Z7q`Wu4k051Testing软件测试网)b4w~4n.[:v&g

        public String toString() {
M9n*}S%Uz0            return String.valueOf(a);
\5|A9s2Kx`0        }51Testing软件测试网}6E |/gF&I lyO.Ii
    }
$sA+D1g;W!P-NvD0   
W+fgq1\0    public static Helper test3() {51Testing软件测试网1j0hE1W'@ RJ
        Helper h = new Helper();51Testing软件测试网6J*kz4[:y|0A8q*zLY
        h.a = 1;

z PD^d{N'~XL0

eJ;d#H @9}R-]0        try{
2s fw ` rEy.j o0            return h;51Testing软件测试网^9i2BW8jM p2Cb
        } catch ( Exception e ) {
51Testing软件测试网G#|1Iu L1z }Dv ^

51Testing软件测试网7KEK%y&V+[

        } finally {51Testing软件测试网PB wV6QXy
            h.a = 2; //对h.a的更改起作用!!
R;p(g(_1Y,y0[:j\)^'~\0              //因为在try里面返回的是一个句柄,它指向的对象的内容 是可以改变的51Testing软件测试网,]M:D(k"^&Z
            System.out.println("do finally");51Testing软件测试网 @/Yg3W6_0T PG$J
        }
B U{`2I7yJ0       
]1x%E#V}`7c4a:q v p0        return h; //这个不会被执行51Testing软件测试网6A'i.h}c8u'D lV
    }

1z|Y+D*`!sl q-|^051Testing软件测试网%d%Y!U4yu9W#m0qy |

    public static Helper test3_1() {51Testing软件测试网z J%Aof3@
        Helper h = new Helper();
+R._2HS_*~0        h.a = 1;
51Testing软件测试网S fj.V9@{

51Testing软件测试网|*VK r8f3F

        try{
Au2q pE[6^0            return h;51Testing软件测试网#s7oG Bk j/XT
        } catch ( Exception e ) {

8y/i P*X'i&[7@R)f4S3Z/w2r051Testing软件测试网9C-ua^`Iu0r!q/p

        } finally {
]2d1i(F*K _0            h.a = 2; //返回a=2,这个不用说了51Testing软件测试网m/EcnJ(?*]?)t
            System.out.println("do finally");
k2j#z!W'HcC*M!D0            return h;
/B];Y{W6p{'Zw0        }
*R;Q2a9k&Ov1~0    }

oH7~BHnZ Un0

ezpx%n051Testing软件测试网/o_)q!wd/J
    /**51Testing软件测试网1{ne-L-l#P5PA4k
     * 总结:51Testing软件测试网Z)dOH%P](A5N:Q
     * return语句,finally里面不建议放return语句,根据需要,可以放在try和catch里面51Testing软件测试网Y;m1vN K{?ap.O
     *
jdyQ5L[k:R0     */
(D1T.vi4qo J:}Qj0   
G:k? gC%a8Ux0}
51Testing软件测试网?"q ^@;Nu8X8|


TAG:

 

评分:0

我来说两句

Open Toolbar