try..catch..finally塊中的跳轉語句(return,break,continue)使用注意事項
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";
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.