2012-04-19 59 views
1

我有一个方法,连接到邮件服务器,获取所有消息,并返回这些消息在数组中。 所以这看起来是这样的(伪):块“终于”在一个方法,返回一个值

public Message[] getMessages() throws Exception { 
    try{ 
     //Connection to mail server, getting all messages and putting them to an array 
     return Message[]; 
    } finally { 
     CloseConnectionToMailServer(); //I don't need it anymore, I just need messages 
    } 
} 

我可以把“回归”指令“最后”块,但这种潜在的禁用例外。 如果我现在离开它,那么“返回”永远不可能达到。

我想你遇到了我跑过的问题。如何获得我需要的所有消息,返回包含这些消息的数组,并以微妙的方式关闭与服务器的连接(甚至是“最佳实践”)?

预先感谢您。

+2

为什么不能达到return语句?如果没有异常,Message []将会被返回。 – Pablo 2012-04-19 18:54:25

+1

为什么不在'try'结束后执行'return Message []'调用?这种方式会更加明显,而不是在方法中嵌入回报。 – 2012-04-19 18:54:43

+2

这真的*不清楚问题在这里。为什么现在不能达到“返回”?请澄清。 – 2012-04-19 18:56:10

回答

3

你的方法很好。即使你从try块返回,finally块也会被执行。 和你的方法必须返回一个值:

public Message[] getMessages() throws Exception { 

    try{ 
     //Connection to mail server, getting all messages and putting them to an array 
     return Message[]; 
    } finally { 
     CloseConnectionToMailServer(); //I don't need it anymore, I just need messages 
    } 

    return null; 
} 
+0

无论如何,终止块将被执行吗? 哦,谢谢,我接近这样的解决方案:) – Dragon 2012-04-19 19:03:03

-2

为什么不这样:

public Message[] getMessages() throws Exception { 
    Message = null; 
    try{ 
     //Connection to mail server, getting all messages and putting them to an array 
     Message = Messages; 
    } finally { 
     CloseConnectionToMailServer(); //I don't need it anymore, I just need messages 
     return Message; 
    } 
} 
+0

消息是一种数据类型而不是对象! – giorashc 2012-04-19 18:58:11

+1

因为如果出现这种情况,finally块中的“return”会消耗一个异常。 – Dragon 2012-04-19 19:01:39

0

'标准' 版本(即我见过)是

try { 
    doStuff() 
} catch (Exception e) { 
    throw e; 
} finally { 
    closeConnections(); 
} 
return stuff; 

我看不出有什么不应该为你的代码工作的原因。作为一个方面说明,如果你的代码是'返回数据'的东西,我一般认为它更容易使它成为'public Message [] getStuff()throws SQLException',然后让调用类处理错误。

相关问题