这个finally块会执行吗?
可能的重复:
在Java中,最后返回trump吗?
我在一个 dao 实现。它返回一个 List,如下所示。
执行“return”语句后,finally 块会尝试关闭会话。这会起作用吗?还是会议将继续举行?
谢谢马克
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
...
public List<Item> findItems(String name) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
try{
Criteria cri = session.createCriteria(Item.class);
return (List<Item>) cri.add(Restrictions.eq("name", name)).list();
} finally {
session.close();
}
}
Possible Duplicate:
In Java, does return trump finally?
I came across a java code snippet in a dao implementation .It returns a List as shown below.
After the 'return' statement is executed,the finally block tries to close the session.Will this work? or will the session remain open?
thanks
mark
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
...
public List<Item> findItems(String name) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
try{
Criteria cri = session.createCriteria(Item.class);
return (List<Item>) cri.add(Restrictions.eq("name", name)).list();
} finally {
session.close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
唯一不会执行finally 块的情况是您终止程序,例如System.exit(0) 或强制退出等。所以答案是:是的,您的会话将被关闭。
The only time a finally block will not be executed is if you terminate your program such as System.exit(0) or force quit etc. So the answer is: Yes, your session will be closed.
阅读 Thefinally 块,是的,finally 块将在
返回
后执行。Read up on The finally Block, and yes, the finally block will be executed after the
return
.是的,
finally
块将始终执行 (*)。finally
块将在return
“之后”执行,因为返回值将在finally<之前被计算和记住。 /code> 块被执行。
(*) 警告:除非有什么原因导致 JVM 完全结束操作。
Yes,
finally
blocks will always execute (*).The
finally
block will execute "after" thereturn
in the sense that the return value will be computed and remembered before thefinally
block is executed.(*) caveat: unless something causes the JVM to end operation alltogether.
是的,finally 块将在
return
语句之后但在值完全返回到方法之前执行。Yes, the finally block will be executed after the
return
statement but before the value is fully returned to the method.