try catch finally

来源:互联网 发布:word2016破解知乎 编辑:程序博客网 时间:2024/05/16 11:43

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);//基本型------2String j=test1();//非基本类型System.out.println("非基本型------"+j);//非基本型------}private static  String test1() {String x="hello";try {System.out.println("A---------"+x);//A---------hellox=x+"world";System.out.println("B---------"+x);//B---------helloworldreturn x;} catch (Exception e) {}finally {System.out.println("C---------"+x);//C---------helloworldx="";System.out.println("D---------"+x);//D---------return x;}}@SuppressWarnings("finally")private static int test() {int x=0;try {System.out.println("A_________"+x);//A_________0x++;System.out.println("B_________"+x);//B_________1return x;} catch (Exception e) {}finally {System.out.println("C________"+x);//C________1x++;System.out.println("D________"+x);//D________2return 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);//基本型------1String j=test1();//非基本类型System.out.println("非基本型------"+j);//非基本型------helloworld}private static  String test1() {String x="hello";try {System.out.println("A---------"+x);//A---------hellox=x+"world";System.out.println("B---------"+x);//B---------helloworldreturn x;} catch (Exception e) {}finally {System.out.println("C---------"+x);//C---------helloworldx="";System.out.println("D---------"+x);//D---------}return "xxxxxx";}@SuppressWarnings("finally")private static int test() {int x=0;try {System.out.println("A_________"+x);//A_________0x++;System.out.println("B_________"+x);//B_________1return x;} catch (Exception e) {}finally {System.out.println("C________"+x);//C________1x++;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的结果




0 0