try..catch..finally块中的跳转语句(return,break,continue)使用注意事项
2012-04-18 18:10
1056 查看
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";
}
}
}
相关文章推荐
- return 于try{}catch(Exception e){}finally{}语句结合使用的一点注意事项。
- return 于try{}catch(Exception e){}finally{}语句结合使用的一点注意事项
- 跳转语句的使用(break,continue,goto,return)
- C#跳转语句(break,continue,return)
- Break,continue,return来实现控制语句的跳转和中断
- java基础之跳转到标号语句的方式(return,break,continue)
- 在Java中使用 break/continue 语句来控制多重嵌套循环的跳转
- Java中break、continue、return语句的使用区别
- [引]C#参考 跳转语句(break,continue,goto,return,throw)
- Java中的跳转控制语句之break、continue、return
- 4 Java基础语法(switch语句,循环语句(for,while),控制跳转语句(break,return,continue))
- 跳转控制语句:关于break,continue,和return的区别
- C#学习 第二章 语句控制,if,switch,try-catch,whlie,foreach,break,continue,goto
- 异常语句:try(尝试)-catch(抓取)-finally 跳转语句:break
- Java中break、continue、return语句的使用区别对比(附实例)
- 在循环中使用break和continue,return语句之间的区别
- Java关于程序跳转语句TestContinueBreakReturn.java
- if,continue,break,while,do-while, switch,return,foreach,for等条件语句的使用
- 跳转控制语句---break,continue,return
- [引]C#参考跳转语句(break,continue,goto,return,throw)