1 return在try
package com.company.exception;
import static com.company.constant.StringConstant.*;
public class ThrowsTest {
private static StringBuilder returnInTry(int a) {
StringBuilder str = new StringBuilder(10);
try{
int b = 1/a;
str.append(TRY);
System.out.println(FROM + str);
return str.append(TRY);
} catch(Exception e) {
str.append(CATCH);
System.out.println(FROM + str);
} finally{
str.append(FINALLY);
System.out.println(FROM + str);
}
return str.append(END);
}
private static void printLine() {
System.out.println("============");
}
public static void main(String[] args) {
StringBuilder str = returnInTry(1);
System.out.println(RESULT + str);
printLine();
StringBuilder str1 = returnInTry(0);
System.out.println(RESULT + str1);
printLine();
}
}
from:try->
from:try->try->finally!
result:try->try->finally!
============
from:catch->
from:catch->finally!
result:catch->finally!
============
2 return在try和catch
package com.company.exception;
import static com.company.constant.StringConstant.*;
public class ThrowsTest {
private static StringBuilder returnInTryAndCatch(int a) {
StringBuilder str = new StringBuilder(10);
try{
int b = 1/a;
str.append(TRY);
System.out.println(FROM + str);
return str.append(TRY);
} catch(Exception e) {
str.append(CATCH);
System.out.println(FROM + str);
return str.append(CATCH);
} finally{
str.append(FINALLY);
System.out.println(FROM + str);
}
}
private static void printLine() {
System.out.println("============");
}
public static void main(String[] args) {
StringBuilder str2 = returnInTryAndCatch(1);
System.out.println(RESULT + str2);
printLine();
StringBuilder str3 = returnInTryAndCatch(0);
System.out.println(RESULT + str3);
printLine();
}
}
from:try->
from:try->try->finally!
result:try->try->finally!
============
from:catch->
from:catch->catch->finally!
result:catch->catch->finally!
============
3 return在try/catch和finally
package com.company.exception;
import static com.company.constant.StringConstant.*;
public class ThrowsTest {
private static StringBuilder returnInTryAndCatchAndFinally(int a) {
StringBuilder str = new StringBuilder(10);
try{
int b = 1/a;
str.append(TRY);
System.out.println(FROM + str);
return str.append(TRY);
} catch(Exception e) {
str.append(CATCH);
System.out.println(FROM + str);
return str;
} finally{
str.append(FINALLY);
System.out.println(FROM + str);
return str.append(FINALLY);
}
}
private static void printLine() {
System.out.println("============");
}
public static void main(String[] args) {
StringBuilder str4 = returnInTryAndCatchAndFinally(1);
System.out.println(RESULT + str4);
printLine();
StringBuilder str5 = returnInTryAndCatchAndFinally(0);
System.out.println(RESULT + str5);
printLine();
}
}
from:try->
from:try->try->finally!
result:try->try->finally!finally!
============
from:catch->
from:catch->finally!
result:catch->finally!finally!
============
4 小结
- try…catch…finally:finally一定会执行
- 顺序执行所有可执行的表达式,包括return中的表达式