-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();
    }
}
Community
  • 1
  • 1
markjason72
  • 1,653
  • 8
  • 27
  • 47

4 Answers4

5

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.

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434
3

Read up on The finally Block, and yes, the finally block will be executed after the return.

Moonbeam
  • 2,283
  • 1
  • 15
  • 17
2

Yes, finally blocks will always execute (*).

The finally block will execute "after" the return in the sense that the return value will be computed and remembered before the finally block is executed.

(*) caveat: unless something causes the JVM to end operation alltogether.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
0

Yes, the finally block will be executed after the return statement but before the value is fully returned to the method.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228