A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© jojo 中级黑马   /  2015-1-9 19:43  /  2008 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 jojo 于 2015-1-10 16:30 编辑

据说能够正确分析出下面这道程序的输出就证明你的Java异常完全没有任何问题了。本以为自己学得还可以,结果瞬间被秒杀了,有兴趣的童鞋可以试试。答案我会附在最后面。

  1. public class TestException {
  2. public TestException() {
  3. }

  4. boolean testEx() throws Exception {
  5. boolean ret = true;
  6. try {
  7. ret = testEx1();
  8. } catch (Exception e) {
  9. System.out.println("testEx, catch exception");
  10. ret = false;
  11. throw e;
  12. } finally {
  13. System.out.println("testEx, finally; return value=" + ret);
  14. return ret;
  15. }
  16. }

  17. boolean testEx1() throws Exception {
  18. boolean ret = true;
  19. try {
  20. ret = testEx2();
  21. if (!ret) {
  22. return false;
  23. }
  24. System.out.println("testEx1, at the end of try");
  25. return ret;
  26. } catch (Exception e) {
  27. System.out.println("testEx1, catch exception");
  28. ret = false;
  29. throw e;
  30. } finally {
  31. System.out.println("testEx1, finally; return value=" + ret);
  32. return ret;
  33. }
  34. }

  35. boolean testEx2() throws Exception {
  36. boolean ret = true;
  37. try {
  38. int b = 12;
  39. int c;
  40. for (int i = 2; i >= -2; i--) {
  41. c = b / i;
  42. System.out.println("i=" + i);
  43. }
  44. return true;
  45. } catch (Exception e) {
  46. System.out.println("testEx2, catch exception");
  47. ret = false;
  48. throw e;
  49. } finally {
  50. System.out.println("testEx2, finally; return value=" + ret);
  51. return ret;
  52. }
  53. }

  54. public static void main(String[] args) {
  55. TestException testException1 = new TestException();
  56. try {
  57. testException1.testEx();
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
复制代码


答案:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

评分

参与人数 1技术分 +1 收起 理由
杨佳名 + 1

查看全部评分

4 个回复

倒序浏览
看不懂,求指导
回复 使用道具 举报
我擦,我的第三和第四步搞反了
回复 使用道具 举报
李忠兵 发表于 2015-1-9 20:41
我擦,我的第三和第四步搞反了

我的打印输出是多了几个,所以才想知道正解是如何出来的
回复 使用道具 举报
finally是肯定会被执行到的(不知道什么原理,记住就好)。
finally的块中有return语句,那么catch中的throw或是return 语句不会被执行。有一点要注意的是,如果catch语句中有return x=1这样的语句,那么x会被赋值为1。
相当于在catch中程序到了throw或return之后就不动了,转而去执行finally,然后回过头来执行catch中的throw和return语句。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马