try catch finally
try 和 catch 只会执行一个,没异常执行try,有异常执行 catch、
finally是一定会执行的、、、
然而恶心的情况来了、当有了return:
分8种情况来讨论:
1、基本类型 非基本类型 try:return finally:return
public class Mytry {
public static void main(String[] args) {
int i=test();//基本类型
System.out.println("基本型------"+i);//基本型------2
String j=test1();//非基本类型
System.out.println("非基本型------"+j);//非基本型------
}
private static String test1() {
String x="hello";
try {
System.out.println("A---------"+x);//A---------hello
x=x+"world";
System.out.println("B---------"+x);//B---------helloworld
return x;
} catch (Exception e) {
}
finally {
System.out.println("C---------"+x);//C---------helloworld
x="";
System.out.println("D---------"+x);//D---------
return x;
}
}
@SuppressWarnings("finally")
private static int test() {
int x=0;
try {
System.out.println("A_________"+x);//A_________0
x++;
System.out.println("B_________"+x);//B_________1
return x;
} catch (Exception e) {
}
finally {
System.out.println("C________"+x);//C________1
x++;
System.out.println("D________"+x);//D________2
return x;
}
}
}
结果:
A_________0
B_________1
C________1
D________2
基本型------2
A---------hello
B---------helloworld
C---------helloworld
D---------
非基本型------
结果:先执行try里面的所有语句,唯独return不执行,等执行完finally,再回过去执行return,可是finally里面已经return了,所以直接返回finally里面的东西;
2、基本类型 非基本类型 try:return finally:NO return
public class Mytry {
public static void main(String[] args) {
int i=test();//基本类型
System.out.println("基本型------"+i);//基本型------1
String j=test1();//非基本类型
System.out.println("非基本型------"+j);//非基本型------helloworld
}
private static String test1() {
String x="hello";
try {
System.out.println("A---------"+x);//A---------hello
x=x+"world";
System.out.println("B---------"+x);//B---------helloworld
return x;
} catch (Exception e) {
}
finally {
System.out.println("C---------"+x);//C---------helloworld
x="";
System.out.println("D---------"+x);//D---------
}
return "xxxxxx";
}
@SuppressWarnings("finally")
private static int test() {
int x=0;
try {
System.out.println("A_________"+x);//A_________0
x++;
System.out.println("B_________"+x);//B_________1
return x;
} catch (Exception e) {
}
finally {
System.out.println("C________"+x);//C________1
x++;
System.out.println("D________"+x);//D________2
}
return 100;
}
}
结果:
A_________0
B_________1
C________1
D________2
基本型------1
A---------hello
B---------helloworld
C---------helloworld
D---------
非基本型------helloworld
从结果上看:不管finally里面执行了什么,均不影响try里面的return的结果