public class TryReturn {
public static void main(String[] args) {
// mtd1()返回1? mtd2()返回2?
// 很可惜,返回的都是3
// 结论: 不要在try..catch..finally块中出现return等跳转出块范围的语句(<<Effective java>>对此问题也有讨论)
System.out.println(mtd1()); // output: 3
System.out.println(mtd2()); // output: 3
}
public static String mtd1() {
try {
return "1";
} catch (Exception e) {
return "2";
} finally {
return "3";
}
}
public static String mtd2() {
try {
throw new Exception();
} catch (Exception e) {
return "2";
} finally {
return "3";
}
}
}
public static void main(String[] args) {
// mtd1()返回1? mtd2()返回2?
// 很可惜,返回的都是3
// 结论: 不要在try..catch..finally块中出现return等跳转出块范围的语句(<<Effective java>>对此问题也有讨论)
System.out.println(mtd1()); // output: 3
System.out.println(mtd2()); // output: 3
}
public static String mtd1() {
try {
return "1";
} catch (Exception e) {
return "2";
} finally {
return "3";
}
}
public static String mtd2() {
try {
throw new Exception();
} catch (Exception e) {
return "2";
} finally {
return "3";
}
}
}