gpt4 book ai didi

java - 返回值的方法中的 block "finally"

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:03 26 4
gpt4 key购买 nike

我有一个方法,它连接到邮件服务器,获取所有消息并以数组形式返回这些消息。所以看起来像这样(伪代码):

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”指令放入“finally” block ,但这会禁用潜在的异常。如果我保持现在的状态,“返回”将永远无法到达。

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

提前谢谢您。

最佳答案

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

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;
}

关于java - 返回值的方法中的 block "finally",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10234810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com