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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© liujkh123 中级黑马   /  2013-5-25 17:19  /  1407 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package com.itheima;

  2. /**
  3. * 第7题:写一个类证明return是在finally执行后才返回的,且在finally无法改变返回值。
  4. * @author Administrator
  5. *
  6. */

  7. /*
  8. * 这道题目一开始挺不清楚什么意思的,后来多查查才知道.
  9. * 在try catch中添加了返回语句的话,finally中就无法再对返回值进行修改了。
  10. * 但是如果在try。。。catch中没有return的话finally则当然可以改变返回值了,
  11. */
  12. public class Test7 {
  13.        
  14.         public static void main(String[] args) {
  15.                 Test7 t7 = new Test7();
  16.                 int i = t7.test();
  17.                 System.out.println("return执行了,但是返回值是:" + i);
  18.         }
  19.        
  20.         public int test(){
  21.                 int i = 0;
  22.                 try{
  23.                         i = 2;                       
  24.                         throw new Exception();                       
  25.                 }catch(Exception e){
  26.                         //e.printStackTrace();
  27.                         i = 3;
  28.                         return i;                       
  29.                 }finally{
  30.                         i= 4;
  31.                         System.out.println("finally执行了!这个时候i的值为" + i );
  32.                 }               
  33.         }
  34.        
  35.         /*这段代码返回的就是4了
  36.         public int test1(){
  37.                 int i = 0;
  38.                 try{
  39.                         i = 2;                       
  40.                         throw new Exception();                       
  41.                 }catch(Exception e){
  42.                         //e.printStackTrace();
  43.                         i = 3;               
  44.                 }finally{
  45.                         i= 4;
  46.                         System.out.println("finally执行了!这个时候i的值为" + i );
  47.                 }
  48.                 return i;
  49.         }
  50.         */
  51. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
袁梦希 + 1 赞一个!

查看全部评分

3 个回复

倒序浏览
这个好像是基础测试题,楼主尽量定义有意义的方法名,不要用test,test1这样命名。

点评

楼下说谢谢老师  发表于 2013-5-25 21:01
回复 使用道具 举报
好的 谢谢老师
回复 使用道具 举报
test(),return返回为3,有点不理解,尽然是4,然后return回到了catch变为了3,我有点不理解,难道是因为return上一句话:i=3吗?
test1(),return返回为4,这个我能懂,是一步一步的走下来,必然是4

楼主你这个问题挺好的,能解释一下吗?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马