你真的了解try-catch-finally么?
try-catch-finally看似是很简单的执行流程,但是如果加上return,结果你能争取判断么?考虑以下代码:
public class ExceptionTest {
public static void main(String[] args) {
String s = null;
try {
s = genString(true);
} finally {
System.out.println(s);
}
}
private static String genString(boolean throwEx) {
try {
if (throwEx) {
throw new RuntimeException("Exception");
}
System.out.println("in try");
return "no exception";
} catch (Exception ex) {
System.out.println("in catch");
return "exception";
} finally {
System.out.println("in finally");
return "finally";
}
}
}
其中genString(boolean)可以决定是否抛异常,在“true”时会打印什么?或者说,genString方法究竟会执行哪条return?传入“false”呢?