-2

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();
    }
}
4

4 回答 4

5

唯一不会执行 finally 块的情况是您终止程序,例如 System.exit(0) 或强制退出等。所以答案是:是的,您的会话将被关闭。

于 2011-07-18T14:02:04.840 回答
3

阅读finally 块,是的,finally 块将在return.

于 2011-07-18T14:02:45.337 回答
2

是的,finally块将始终执行 (*)。

块将finally在“之后”执行return,因为返回值将在块执行之前被计算和记住。finally

(*) 警告:除非有什么东西导致 JVM 一起结束操作。

于 2011-07-18T14:03:09.397 回答
0

是的,finally 块将在return语句之后但在值完全返回到方法之前执行。

于 2011-07-18T14:05:35.683 回答