try-catch-finally的问题

昨天遇到一个问题,在try-catch里面如果在try方法块和finaly方法块里面同时设置return返回值,finally里面的返回值会将try里面的返回值覆盖。如下面的sample

public String test1()

{

String a = null;

    try 

    {

     APLog.e("test1""try1");

        System.out.println(a);//遇到异常就跳转了

        APLog.e("test1""try2");//这里不会执行到

        return "1";

    } 

    catch (Exception e) 

    {

     APLog.e("test1""catch");

    }

    finally

    {

        System.out.println("b");

     APLog.e("test1""finally");

        return "2";

    }

}

上面的例子里面,finally里面的return,会覆盖掉try里面的返回值。运行结果如下:

运行结果:

04-26 14:11:00.130: E/(510): test1 | try1

04-26 14:11:00.130: E/(510): test1 | catch

04-26 14:11:00.130: E/(510): test1 | finally


同时finall块中包含return语句时,Eclipse会给出警告“finally block does not complete normally”,原因分析是:

1、不管try块、catch块中是否有return语句,finally块都会执行。
2、finally块中的return语句会覆盖前面的return语句(try块、catch块中的return语句),所以如果finally块中有return语句,Eclipse编译器会报警告“finally block does not complete normally”。

3、如果finally块中包含了return语句,即使前面的catch块重新抛出了异常,则调用该方法的语句也不会获得catch块重新抛出的异常,而是会得到finally块的返回值,并且不会捕获异常。

结论,finally 内部使用 return 语句是一种很不好的习惯,如果try中还有return语句,它会覆盖了try 区域中 return 语句的返回值,程序的可读性差

面对上述情况,其实更合理的做法是,既不在 try block 内部中使用 return 语句,也不在 finally 内部使用 return 语句,而应该在 finally 语句之后使用 return 来表示函数的结束和返回

 

这里查阅了原贴http://blog.csdn.net/luckarecs/article/details/7214826


同时记录下,如果在try-catch里面,有finally,那么即使没有catch住异常,程序也不糊crash掉,如果没有finally的处理,那么如果没有catch住异常,程序就会crash。

如下面:

testA不会crash,testB会crash

 

public String testA()

{

int[] a = {1,2,3};

    try 

    {

     APLog.e("test1""try1");

        System.out.println(a[4]);

        APLog.e("test1""try2");

        return "1";

    } 

    catch (NullPointerException e) 

    {

     APLog.e("test1""catch");

    }

    finally

    {

     return "2";

    }

    

}

 

public String testB()

{

int[] a = {1,2,3};

    try 

    {

     APLog.e("test1""try1");

        System.out.println(a[4]);

        APLog.e("test1""try2");

        return "1";

    } 

    catch (NullPointerException e) 

    {

     APLog.e("test1""catch");

    }

    

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值