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;