finally 浅谈

近日做程序时突发奇想:try ... finally ... 中的 finally 会在返回前执行(在XXX书上看到的,忘了书名了),是于做了以下测试

public class FinallyTest
{
public static void main(String args[])
{
System.out.println("return: " + new FinallyTest().getString());
}

public String getString()
{
String returnString = null;
try
{
returnString = "this string will be return.";
return returnString;
}finally
{
System.out.println("execute finally...");
System.out.println("before clean returnString's value: " + returnString);
returnString = null;
System.out.println("after clean returnString's value: " + returnString);
System.out.println("execute finally end.");
}
}
}

测试结题:

execute finally...
before clean returnString's value: this string will be return.
after clean returnString's value: null
execute finally end.
return: this string will be return.

如果返回前执行,那么返回的字符串应该为空。但从结果来看,似乎出人的意料之外。
考虑原因:返回前将返回的结果拷贝了。

于是做了以下修改:

public class FinallyTest
{
public static void main(String args[])
{
System.out.println("return: " + new FinallyTest().getMessage().message);
}

public Message getMessage()
{
Message returnMessage = new Message();
try
{
returnMessage.message = "message";
return returnMessage;
}finally
{
System.out.println("execute finally...");
System.out.println("before clean returnString's value: " + returnMessage.message);
returnMessage.message = null;
System.out.println("after clean returnString's value: " + returnMessage.message);
System.out.println("execute finally end.");
}
}
}

class Message
{
public String message = "message";
}


结果:

execute finally...
before clean returnString's value: message
after clean returnString's value: null
execute finally end.
return: null

从结果来看,只调用了对象的引用,而对象没有被拷贝。
看来,如所下用 finally 统一处理一般数据类型还是免谈了。

public class FinallyTest
{
public static void main(String args[])
{
System.out.println("return: " + new FinallyTest().getInt());
}

public int getInt()
{
int returnInt = 0;
try
{
returnInt = 1;
throw new RuntimeException("...");
}catch(Exception e)
{
returnInt = 2;
return returnInt;
}finally
{
System.out.println("execute finally...");
System.out.println("before switch returnInt's value: " + returnInt);
switch(returnInt)
{
case 1:
returnInt = 0;
break;
case 2:
returnInt = 3;
break;
default:
returnInt = 4;
}
System.out.println("after switch returnInt's value: " + returnInt);
System.out.println("execute finally end.");
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值